首页 > 解决方案 > 按钮元素可以有子节点吗?

问题描述

如果我有一个<b>内部<button>标签,那么是标签<b>的 childNode<button>吗?考虑下面的代码:

<button id='mooo'><b>Cows can't mooo</b></button>

Javascript:

x = document.getElementById('mooo');
x.addEventListener("Click", mooo);

function mooo(e){
if(e.target.childNode == "B"){
console.log("B is a child of Button");
}else{
console.log("B is not a child of Button");
}

代码返回后者,但我只需要确定 B 是否确实不是 BUTTON 的孩子

标签: javascripthtmldomnodes

解决方案


是的,button元素是有内容的元素。您只是没有正确检查他们的内容;元素没有childNode属性。有childNodes(一个集合)、firstChildlastChild和它们的元素版本childrenfirstElementChild、 和lastElementChild,但没有childNode

您还使用Click了而不是click(事件名称区分大小写),e.target它可能是b元素而不是button(您希望thise.currentTarget知道您正在引用button)。

现场示例:

var x = document.getElementById('mooo');
x.addEventListener("click", mooo);

function mooo() {
  if (this.firstElementChild.tagName == "B") {
    console.log("B is a child of Button");
  } else {
    console.log("B is not a child of Button");
  }
  console.log("Contents of the button:");
  for (let child = this.firstChild; child; child = child.nextSibling) {
    switch (child.nodeType) {
      case 1: // Element
        console.log(child.tagName + " element, innerHTML = " + child.innerHTML);
        break;
      case 3: // Text node
        console.log("Text node, nodeValue = " + child.nodeValue);
        break;
      default:
        console.log(child.nodeName);
        break;
    }
  }
}
<button id='mooo'><b>Cows can't mooo</b></button>

相反,input type="button"元素是无效元素;他们没有内容,他们的childNodes收藏总是空的。


推荐阅读