首页 > 解决方案 > 将 getElementById 更改为 getElementsByClassName [未定义]

问题描述

我在使用getElementsByClassName. 单击添加按钮时,它会以 nameundefined而不是 value出现在列表中"hello"。我究竟做错了什么?

代码:

function addItem(){
  var ul = document.getElementById("dynamic-list");
  var candidate = document.getElementsByClassName("candidate");
  var li = document.createElement("li");
  li.setAttribute('class',candidate.value);
  li.appendChild(document.createTextNode(candidate.value));
  ul.appendChild(li);
}

function removeItem(){
  var ul = document.getElementById("dynamic-list");
  var candidate = document.getElementsByClassName("candidate");
  var item = document.getElementsByClassName(candidate.value);
  ul.removeChild(item);
}
<ul id="dynamic-list"></ul>
<button type="submit" class="item" value="hello" onclick="addItem()">ADD</button>
<button onclick="removeItem()">remove item</button>

标签: javascripthtml

解决方案


您的代码的主要问题是类名candidate在您的 HTML 中的任何位置都不存在。如果您的目标是使用此类引用“添加”按钮,那么您需要candidate在 HTML 中将其类更改为,或更改您的 JS 以引用其实际类,item.

此外,getElementsByClassName顾名思义,返回多个NodeList元素的 a ,而不是单个元素。这意味着您需要从该列表中选择一个要对其进行操作的元素;相反,您的代码将此方法视为仅返回一个要直接操作的元素(即 a而不是 a )。对于您的功能,此更改是微不足道的;该类只有一个元素,因此只需选择(即 element )的第一个元素。对于该函数,假设您要首先删除最近添加的节点(LIFO 样式),您需要删除NodeNodeListaddItemitemNodeList0removeItemNodeList(如果存在的话)来自 DOM。有关所有这些更改和一些解释性评论,请参阅下面的更新片段:

function addItem(){
  var ul = document.getElementById("dynamic-list");
  // We know that the "candidate" is always the first—and only—element with the class name "item"
  var candidate = document.getElementsByClassName("item")[0];
  var li = document.createElement("li");
  li.setAttribute('class',candidate.value);
  li.appendChild(document.createTextNode(candidate.value));
  ul.appendChild(li);
}

function removeItem(){
  var ul = document.getElementById("dynamic-list");
  // We know that the "candidate" is always the first—and only—element with the class name "item"
  var candidate = document.getElementsByClassName("item")[0];
  // The "items" variable is introduced to hold the list of all added ".hello" elements, the last of which we will remove
  var items = document.getElementsByClassName(candidate.value);
  // Safety check: it's possible that there are no more ".hello" elements remaining, in which case there's nothing to remove
  if (items.length > 0) {
    // Access the last element of the NodeList and remove it from the DOM
    var item = items[items.length - 1];
    ul.removeChild(item);
  }
}
<ul id="dynamic-list"></ul>
<button type="submit" class="item" value="hello" onclick="addItem()">ADD</button>
<button onclick="removeItem()">remove item</button>


推荐阅读