【问题标题】:Getting "document.getElementByClassName is not a function" error in console [duplicate]在控制台中出现“document.getElementByClassName 不是函数”错误 [重复]
【发布时间】:2019-11-11 19:29:15
【问题描述】:

关于如何解决此错误的任何想法:“document.getElementByClassName 不是函数”

代码如下:

HTML:

<a href="#" class="filter-btn" onclick="myFunction()" data-filter="opd-list-id-<?php echo $item->ID; ?>" style="background:<?php echo $filter_background_color ?>;color:<?php echo $filter_text_color ?> !important;">

JS

function myFunction() {
var elmnt = document.getElementByClassName("filter-btn");
elmnt.scrollIntoView(); 
}

【问题讨论】:

  • 您正在寻找getElementsByClassName。注意元素上的“s”
  • @Nick 立即注意到了同样的事情 +1
  • 如果您有错误消息,那么您应该做的第一件事是搜索该错误,并检查是否已经存在针对该问题的问题。如果那个不能帮助你解决问题,那么你应该解释原因。

标签: javascript html css wordpress


【解决方案1】:

getElementByClassName 替换为getElementsByClassName

注意它的复数(Elements)以“s”结尾而不是单数(Element

可以将同一个类添加到多个对象,因此,按类名选择会返回多个项目,而不仅仅是一个,因此它使用复数形式 Elements 而不是 Element,就像 getElementById() 一样,因为 id 必须是唯一的,并且按 id 选择只会返回一个 DOM 元素

并且,由于函数 getElementsByClassName 返回一个元素数组 elmnt.scrollIntoView() 将不起作用,
所以你需要使用数组的第一个元素为elmnt[0]

所以你的代码将是

function myFunction() {
  var elmnt = document.getElementsByClassName("filter-btn");
  elmnt[0].scrollIntoView(); 
}

但是,如果您只想选择一个元素并按以下方式使用,我宁愿建议使用getElementById(首先将id IdGivenToTheAnchoreTag 赋予锚标记)

function myFunction() {
  var elmnt = document.getElementById("IdGivenToTheAnchoreTag");
  elmnt.scrollIntoView(); 
}

【讨论】:

  • 知道了,改成 Elements,谢谢。但是现在得到如下错误:Uncaught TypeError: elmnt.scrollIntoView is not a function
  • 什么错误?你忘记粘贴了吗?
  • 查看我的更新答案!
  • +1;您可能希望将 [0] 放在 elmnt 声明的结尾之前;不在 .scrollIntoView(); 之前。
  • will return only one DOM DOM 表示 文档对象模型 你的意思是一个 DOMElement
【解决方案2】:

您正在寻找getElementsByClassName。注意元素上的“s”

function myFunction() {
  var elmnt = document.getElementsByClassName("filter-btn");
  test.scrollIntoView();  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    相关资源
    最近更新 更多