Коллекция NodeList / HTML, возвращаемая из свойства .children
, состоит из прямых потомков parentElement (ie children - not children of children ). Если вы хотите использовать .children
, чтобы добраться до "внуков" , вам нужно будет выполнить итерацию по обоим .children
коллекциям или, если вы имеете в виду childElement, тогда будет использоваться скобочная запись (например, parentElement.children[1]
) BTW номер индекса в скобочных обозначениях основан на 0-индексе, поэтому, например, .children[2]
на самом деле является третьим элементом и т. Д.
Демо
// Reference the <ul>
const list = document.querySelector('.list');
/*
Collect each <li> in <ul> into a NodeListr then
convert it into a real Array with the bracket and
spread operator (ie [...NodeList]
*/// itemsA and itemsB are identical
const itemsA = [...list.querySelectorAll('.item')];
const itemsB = [...list.children];
/*
Since the OP objective was vague...the following are console logs that verify the results.
The last console log is my best guess as to what the OP's objective was.
*/
console.log(` .list direct descendants (aka children):\n
${itemsB.map(item => ` <${item.tagName.toLowerCase()} class="${item.className}">...<\/${item.tagName.toLowerCase()}>\n`)}`);
console.log(`Array itemsA (as htmlString):\n
${itemsA.map(item => item.outerHTML)}`);
console.log(`Array itemsB (as htmlString):\n
${itemsB.map(item => item.outerHTML)}`);
console.log(`Third .item of .list (as htmlString):\n
${itemsA[2].outerHTML}`);
console.log(`Third .item of .list deepest descendant:\n
${[...itemsB[2].children].flatMap((node, index) => node.children[index].outerHTML)}`);
.list {
list-style: none
}
.item {
margin-bottom: 14px
}
.as-console-wrapper {
width: 375px;
min-height: 100%;
margin-left: 25%;
}
.as-console-row {
border-bottom: 5px ridge #333
}
.as-console-row-code::first-line {
text-decoration: underline;
}
.as-console-row.as-console-row::after,
.as-console-row-code.as-console-row-code::after {
content:'';
padding:0;
margin:0;
border:0;
width:0;
}
<link href="https://use.fontawesome.com/releases/v5.12.1/css/all.css" rel="stylesheet" crossorigin="anonymous">
<ul class="list">
<li class="item">
<a class="link" href="#/">
ITEM 1 <i class="fas fa-minus-square"></i>
</a>
</li>
<li class="item">
<a class="link" href="#/">
ITEM 2 <i class="fas fa-minus-square"></i>
</a>
</li>
<li class="item">
<a class="link" href="#/">
ITEM 3 <i class="fas fa-minus-square"></i>
</a>
</li>
</ul>