Jam*_*oyi 0 html javascript dom nodes
如果我有<b>内部<button>标签,那么它是标签<b>的childNode <button>吗?考虑以下代码:
<button id='mooo'><b>Cows can't mooo</b></button>
Run Code Online (Sandbox Code Playgroud)
使用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");
}
Run Code Online (Sandbox Code Playgroud)
代码返回后者,但我只需要确定B是否确实不是BUTTON的孩子
是的,button元素是包含内容的元素.你只是没有正确检查他们的内容; childNode元素没有属性.有childNodes(集合), ,firstChild,lastChild和他们的元素版本children,firstElementChild以及lastElementChild,但没有childNode.
你也使用Click而不是click(事件名称区分大小写),e.target它可能是b元素而不是button(你想要this或e.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;
}
}
}Run Code Online (Sandbox Code Playgroud)
<button id='mooo'><b>Cows can't mooo</b></button>Run Code Online (Sandbox Code Playgroud)
相比之下,input type="button"元素是空白元素 ; 他们不能拥有内容,他们的childNodes收藏总是空的.