批改状态:合格
老师批语:
<body><ul class="list"><li class="item">item1</li><li class="item">item2</li><li class="item">item3</li><li class="item">item4</li><li class="item">item5</li></ul>
<script>let ul = document.querySelector(".list");console.log(ul);console.log(ul.childNodes);
先使用querySelector(“.list”)获取ul元素。为了获取ul的子元素可以使用childNodes方法,结果是:
返回的Nodelist共有11个,原因是节点类型包括了很多中,例如,元素,文本,属性,注释等。
用children比较好console.log(ul.children);返回五个元素
console.log(ul.children[0].textContent);ul.children[0].style.background = "red";
上面的方法可以获得ul第一个子元素的文本,通过style可以控制样式。
Array.from能够将上面的元素集合转化为一个真正的数组。
下面比较一下
console.log(ul.children);console.log(Array.from(ul.children));

还有更加简单的一种方式console.log([...ul.children]);
效果是一样的。
ul.firstElementChild.style.background = "yellow";ul.firstElementChild.nextElementSibling.style.background = "red";ul.lastElementChild.previousElementSibling.style.background = "wheat";ul.lastElementChild.style.background = "cyan";ul.lastElementChild.parentElement.style.border = "4px solid";ul.lastElementChild.parentNode.style.border = "4px solid green";</script>

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号