1. 程式人生 > >【前端】遍歷DOM

【前端】遍歷DOM


// 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);

這裡面重點突出兩個要點:

  • parentNodeparentElement效果相同
  • xxxChild, xxxSibling 不推薦使用,推薦的是xxxElementChild, xxxElementSibling

END.