【问题标题】:Difference between getElementById and getElementsByClassName [duplicate]getElementById 和 getElementsByClassName 之间的区别 [重复]
【发布时间】:2017-10-03 10:45:42
【问题描述】:

我已经写了一个javascript语句:

var n=document.getElementById("image");

此代码不起作用。但是当我将 id 更改为 class 和语句时:

var n=document.getElementsByClassName("image");

它工作得很好。谁能解释为什么我不能对 id 做同样的事情..

提前致谢

注意:当我说工作时,我的意思是变量“n”存储了一些值。

【问题讨论】:

  • getElementById 返回单个元素,getElementsByClassName 返回 html 元素集合
  • 你也可以给我们看看html代码吗?

标签: javascript html node.js


【解决方案1】:

确保在使用getElementById 时,页面中只有一个 ID 实例,因为它只获得第一个匹配项。而getElementByClassName 获取该类的所有元素。

ID - 在页面中必须是唯一的

类 - 可以尽可能多次使用

Demo

【讨论】:

    【解决方案2】:

    在 Html 中,有两种方法可以识别 html 标签的特定实例与一组 html 元素。我们以div 为例。

    如果我们要在 UI 上的某处有一个导航栏,并且它将是我们将拥有的唯一导航栏,那么我们将使用 html id 来实现它。

    如果我们说的是一组内容,那么我们会将所有显示内容的 div 标记为 class

    例如,假设我们有一个导航栏和 3 个内容框。 html 看起来像:

    <div id="navbar">stuff</div>
    <div class="content"> content stuff</div>
    <div class="content"> content stuff</div>
    <div class="content"> content stuff</div>
    

    在 JS 方面,如果我们使用 document.getElementById(),我们只能定位 navbar,因为只有 1 个 html id 标签。但是,如果我们想要获取内容 div 组,这意味着使用 document.getElementByClassName(),并且由于存在多个类,我们将返回一个包含 content 类的 html div 的数组。

    所以它确实取决于你的 html。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-16
      • 2011-04-08
      • 2012-11-24
      • 2013-06-05
      • 2021-09-29
      • 2020-05-27
      • 2016-03-23
      • 2012-08-11
      相关资源
      最近更新 更多