Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Today we’ll review the API for getting parent, child, and sibling elements in the DOM, They mainly include parentNode, firstChild, firstElementChild, lastChild, lastElementChild, childNodes, Children, nextElementSibling, and nextSibli Ng, previousElementSibling, previousSibling, etc.

directory

  • Gets the parent element – parentNode

  • Gets the child elements -firstChild, firstElementChild, lastChild, lastElementChild, childNodes, children

  • Get sibling elements – nextElementSibling, nextSibling, previousElementSibling, previousSibling

Get the parent element

ParentNode properties

To get the parent of the specified node in the DOM tree, we can use the parentNode property

let parent = node.parentNode;
Copy the code

ParentNode is read-only

Document and DocumentFragment have no parentNode, so the parentNode property will be null.

ParentNode example

Here is a simple page

<! DOCTYPEhtml>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript parentNode</title>
</head>
<body>
  <div id="main">
    <p class="note">This is a paragraph</p>
  </div>

  <script>
    let note = document.querySelector('.note');
    console.log(note.parentNode);
  </script>
</body>
</html>
Copy the code

Console print results

The parentNode property is also null if there is no specified element and no parent element.

Get child elements

<! DOCTYPEhtml>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Child Elements</title>
</head>
<body>
  <ul id="menu">
    <li class="first">Home page</li>
    <li>product</li>
    <li class="current">news</li>
    <li>blog</li>
    <li>investors</li>
    <li>The document</li>
    <li class="last">About us</li>
  </ul>
</body>
</html>
Copy the code

firstChild

Gets the firstChild of the specified element, using the firstChild attribute

let firstChild = parentElement.firstChild; 
Copy the code

FirstChild returns NULL if the parent element does not have any children. The firstChild attribute returns a child node, which can be any node type, such as an element node, text node, or comment node.

let content = document.getElementById('menu');
let firstChild = content.firstChild.nodeName;
console.log(firstChild);

/ / output:
// #text
Copy the code

The code above prints #text instead of the LI node because there is a blank space between ul and li.

Any Spaces in THE HTML (single space, multiple Spaces, carriage returns, and tabs) will create a #text node. To remove the #text node, remove Spaces, as shown below

<ul id="menu"><li class="first">Home page</li><li>product</li></ul>
Copy the code

If I want to get a child node of the first element type, we can use the firstElementChild attribute

let firstElementChild = parentElement.firstElementChild;
Copy the code

The following code outputs the first LI element

let content = document.getElementById('menu');
console.log(content.firstElementChild);

/ / output:
// 
  • Copy the code

    lastChild

    Similarly, to get the lastChild of a node, we use the lastChild attribute

    let lastChild = parentElement.lastChild;
    Copy the code

    As with firstChild, if you want to get the last child element, use the lastElementChild attribute

    let lastChild = parentElement.lastElementChild;
    Copy the code

    The following code will return the last LI element of the UI

    let menu = document.getElementById('menu');
    console.log(menu.lastElementChild);
    
    / / output:
    
  • Copy the code

    childNodes

    Gets NodeList, the child of the specified element, using the childNodes attribute

    let children = parentElement.childNodes;
    Copy the code

    FirstChild, lastChild

    The childNodes property returns all child elements of any node type. To get only the children of the element node type, use the children attribute:

    let children = parentElement.children;
    Copy the code

    The following code gets all the child elements under ul

    let menu = document.getElementById('menu');
    let children = menu.children;
    console.log(children);
    Copy the code

    The output is shown below.

    Sibling elements

    How do we get the next sibling of an element, the previous sibling, and all sibling elements if our HTML structure looks like this

    <ul id="menu">
      <li>Home page</li>
      <li>product</li>
      <li class="current">news</li>
      <li>blog</li>
      <li>investors</li>
      <li>The document</li>
      <li>About us</li>
    </ul>
    Copy the code

    Next sibling element

    To get the next sibling element, use the nextElementSibling attribute

    let nextSibling = currentNode.nextElementSibling;
    Copy the code

    NextElementSibling returns NULL if you specify that the element is the last one below the parent.

    let current = document.querySelector('.current');
    let nextSibling = current.nextElementSibling;
    console.log(nextSibling);
    
    / / output:
     
    Copy the code

    We can add a while loop to get all the next siblings of the specified element

    let current = document.querySelector('.current');
    let nextSibling = current.nextElementSibling;
    
    while(nextSibling) {
      console.log(nextSibling);
      nextSibling = nextSibling.nextElementSibling;
    }
    Copy the code

    The previous sibling element

    Similarly, get the last sibling using the previousElementSibling attribute

    let current = document.querySelector('.current');
    let prevSibling = currentNode.previousElementSibling;
    Copy the code

    PreviousElementSibling returns NULL if the specified element is the first element under the parent.

    let current = document.querySelector('.current');
    let prevSiblings = current.previousElementSibling;
    console.log(prevSiblings);
    
    / / output:
    // 
  • Copy the code

    Similarly, to get all the last neighboring siblings of a given element, we can add a while loop

    let current = document.querySelector('.current');
    let prevSibling = current.previousElementSibling;
    while(prevSibling) {
      console.log(prevSibling);
      prevSibling = prevSibling.previousElementSibling;
    }
    Copy the code

    Gets all sibling elements

    To get all siblings of a given element, we can follow the logic

    • The parent element of the specified element is searched first. If it does not return, there are no sibling elements
    • The second gets the first child node under the parent element
    • Third, add the first element tosiblingsIn the array
    • Fourth selects the next sibling of the first element
    • Finally, loop steps three and four until there is no next sibling element node
    let getSiblings = function (e) {
      // Store all sibling elements
      let siblings = []; 
      // If there is no parent element, return
      if(! e.parentNode) {return siblings;
      }
      // The first child of the parent element
      let sibling  = e.parentNode.firstChild;
    
      // loop to record all sibling elements
      while (sibling) {
        if (sibling.nodeType === 1&& sibling ! == e) { siblings.push(sibling); } sibling = sibling.nextSibling; }return siblings;
    };
    Copy the code

    The sample code

    <! DOCTYPEhtml>
    <html>
    <head>
        <meta charset="utf-8">
        <title>JavaScript Siblings</title>
    </head>
    <body>
      <ul id="menu">
        <li>Home page</li>
        <li>product</li>
        <li class="current">news</li>
        <li>blog</li>
        <li>investors</li>
        <li>The document</li>
        <li>About us</li>
      </ul>
        
      <script>
        let getSiblings = function (e) {
          // Store all sibling elements
          let siblings = []; 
          // If there is no parent element, return
          if(! e.parentNode) {return siblings;
          }
          // The first child of the parent element
          let sibling  = e.parentNode.firstChild;
    
          // loop to record all sibling elements
          while (sibling) {
            if (sibling.nodeType === 1&& sibling ! == e) { siblings.push(sibling); } sibling = sibling.nextSibling; }return siblings;
        };
    
        let siblings = getSiblings(document.querySelector('.current'));
        siblingText = siblings.map(e= > e.innerHTML);
        console.log(siblingText);
      </script>
    </body>
    </html>
    Copy the code

    The above code will print:

    [' Home ', 'Product ',' Blog ', 'Investor ',' Documentation ', 'About Us ']Copy the code

    conclusion

    These basic DOM manipulation apis are usually used by most people. They are all based on JQuery or MVVM frameworks such as Vue and React. However, you should understand that the underlying principle of these technologies is also very basic DOM manipulation, but it does the dirty work for you.

    That’s it for today, and tomorrow we’ll talk about dynamic DOM element creation and dynamic insertion.

    If you want to review DOM knowledge with me, wechat search [Xiaoshuai’s programming notes], updated every day