Может ли элемент кнопки иметь дочерние узлы? - PullRequest
0 голосов
/ 26 мая 2018

Если у меня есть <b> внутри <button> тегов, является ли <b> дочерним узлом тегов <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

1 Ответ

0 голосов
/ 26 мая 2018

Да, 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;
    }
  }
}
<button id='mooo'><b>Cows can't mooo</b></button>

Напротив, input type="button" элементы пустые элементы ;у них не может быть контента, их коллекция childNodes всегда пуста.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...