this.element.querySelectorAll('li') vs this.element.children 其中所有 children 都是 LI

this.element.querySelectorAll('li') vs this.element.children where all children are LI

当所有 children 都是 'li' 元素时,为什么 this.el.children 在 this.el.querySelectorAll('li') 时不起作用;是吗?

例如:

function RadioGroup(id) {
this.el = document.querySelector(id);
this.buttons = slice(this.el.querySelectorAll('.radio'));
this.focusedIdx = 0;
this.focusedButton = this.buttons[this.focusedIdx];

this.el.addEventListener('keydown', this.handleKeyDown.bind(this));
this.el.addEventListener('click', this.handleClick.bind(this));

this.el.setAttribute('role', 'radiogroup');

// This works
this.el.querySelectorAll('li').forEach(function (item){
  item.setAttribute('role', 'radio');
});

// But this doesn't
this.el.children.forEach(function (item){
  item.setAttribute('role', 'radio');
});
}

这里是 HTML:

  <ul id="group1" class="radiogroup">
    <li class="radio">Water</li>
    <li class="radio">Tea</li>
    <li class="radio">Coffee</li>
    <li class="radio">Cola</li>
    <li class="radio">Ginger Ale</li>
  </ul>

Element.querySelectorAll returns 确实包含 forEach 方法的 NodeList,而 Node.childrenHTMLCollection 且不包含forEach.

[1] https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
[2] https://developer.mozilla.org/en-US/docs/Web/API/NodeList

[3] https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/children
[4] https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection

使用 ES6 的扩展运算符,您可以使两者以相同的方式工作。

function RadioGroup(id) {
this.el = document.querySelector(id);
this.buttons = slice(this.el.querySelectorAll('.radio'));
this.focusedIdx = 0;
this.focusedButton = this.buttons[this.focusedIdx];

this.el.addEventListener('keydown', this.handleKeyDown.bind(this));
this.el.addEventListener('click', this.handleClick.bind(this));

this.el.setAttribute('role', 'radiogroup');

// This works
[...this.el.querySelectorAll('li')].forEach(function (item){
  item.setAttribute('role', 'radio');
});

// And this too ;-)
[...this.el.children].forEach(function (item){
  item.setAttribute('role', 'radio');
});
}