DOM Navigation in JS

DOM navigation = the process of navigating through the structure of an HTML document using JS.

.firstElementChild
.lastElementChild
.nextElementSibling
.previousElementSibling
.parentElement
.children
<!-- ==================== HTML 结构 ==================== -->
 
<!-- 水果列表 -->
<ul id="fruits">
  <li id="apple">apple</li>
  <li id="orange">orange</li>
  <li id="banana">banana</li>
</ul>
 
<!-- 蔬菜列表 -->
<ul id="vegetables">
  <li id="carrots">carrots</li>
  <li id="onions">onions</li>
  <li id="potatoes">potatoes</li>
</ul>
 
<!-- 甜品列表 -->
<ul id="desserts">
  <li id="cake">cake</li>
  <li id="pie">pie</li>
  <li id="ice cream">ice cream</li>
</ul>
 
<script>
  // ==================== 选择元素 ====================
 
  // 选中页面上所有的 <ul> 元素(NodeList)
  const ulElements = document.querySelectorAll("ul");
 
  // 获取 id 为 "vegetables" 的 <ul> 元素
  const element = document.getElementById("vegetables");
 
  // ==================== .firstElementChild ====================
  // 访问该元素的第一个子元素
  const firstChild = element.firstElementChild;
  // 改变它的背景颜色
  firstChild.style.backgroundColor = "yellow";
 
  // 遍历每一个 <ul>,让每个列表的第一个子元素都变红
  ulElements.forEach(ulElement => {
    const firstChild = ulElement.firstElementChild;
    firstChild.style.backgroundColor = "red";
  });
 
  // ==================== .lastElementChild ====================
  // 获取指定 <ul> 的最后一个子元素
  const lastChild = element.lastElementChild;
  lastChild.style.backgroundColor = "blue";
 
  // 遍历每个 <ul>,让每个列表的最后一个子元素变成棕色
  ulElements.forEach(ulElement => {
    const lastChild = ulElement.lastElementChild;
    lastChild.style.backgroundColor = "brown";
  });
 
  // ==================== .nextElementSibling ====================
  // 获取下一个兄弟元素(vegetables 的下一个是 desserts)
  const nextSibling = element.nextElementSibling;
  nextSibling.style.backgroundColor = "lightyellow";
 
  // 获取上一个兄弟元素(vegetables 的上一个是 fruits)
  const prevsibling = element.previousElementSibling;
  prevsibling.style.backgroundColor = "lightblue";
 
  // ==================== .parentElement ====================
  // 获取父节点(这里的父节点是 <body>)
  const parent = element.parentElement;
  parent.style.backgroundColor = "black"; // 给整个页面背景上色
 
  // ==================== .children ====================
  // 获取所有子元素(HTMLCollection)
  const children = element.children;
 
  // 输出 HTMLCollection 对象(类似数组)
  console.log(children);
 
  // 转换为真正的数组以便使用 forEach 遍历
  console.log(Array.from(children));
 
  // 遍历蔬菜列表的所有子项,让每个 <li> 背景变黄
  Array.from(children).forEach(child => {
    child.style.backgroundColor = "yellow";
  });
</script>