版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011240016/article/details/84140554
// parentNode
var itemList = document.querySelector('#items');
console.log(itemList.parentNode);
itemList.parentNode.style.backgroundColor = "#f4f4f4";
console.log(itemList.parentNode.parentNode);
// parentElement -- 一般等价于parentNode
var itemList = document.querySelector('#items');
console.log(itemList.parentElement);
itemList.parentNode.style.backgroundColor = "#f4f4f4";
console.log(itemList.parentElement.parentElement);
// childNodes -- 不建议使用,因为会把换行作为text元素,推荐使用children
console.log(itemList.childNodes)
console.log(itemList.children);
console.log(itemList.children[1].textContent);
itemList.children[1].style.backgroundColor = 'yellow';
// // firstChild -- 无用
console.log(itemList.firstChild)
// firstElementChild -- 推荐
console.log(itemList.firstElementChild);
itemList.firstElementChild.textContent = "First";
// // lastChild -- 无用
console.log(itemList.lastChild);
// // lastElementChild -- 推荐
console.log(itemList.lastElementChild);
itemList.lastElementChild.textContent = "Last";
nextSibling -- 还是不推荐,有换行内容
console.log(itemList.nextSibling);
// // nextElementSibling -- 推荐
console.log(itemList.nextElementSibling);
// previousSibling -- 无用
console.log(itemList.previousSibling);
// previousElementSibling -- 推荐
console.log(itemList.previousElementSibling);
这里面重点突出两个要点:
parentNode
与parentElement
效果相同xxxChild, xxxSibling
不推荐使用,推荐的是xxxElementChild, xxxElementSibling
END.