Day 33 of #100daysofjs

Element only Navigation

Element only navigation

Sometimes we don't want text or comment nodes. Some links only take Element nodes into account. For example:

  • firstElementChild - Returns the first child element of the specified element.

  • lastElementChild - Returns the last child element of the specified element.

  • previousElementSibling - Returns the previous sibling element of the specified element.

  • nextElementSibling - Returns the next sibling element of the specified element.

Lets see this in action, we will use the following HTML code:

<!DOCTYPE html>
<html>
<head>   
<title>Portfolio</title>    
<link rel="stylesheet" href="style.css">
</head>
<body>  
 <nav>   
 <ul>      
  <li>Home</li>     
   <li>About me</li>    
   <li>Hire me</li>  
  </ul> 
  </nav> 
   <div class="container">   
 <p>Hey, this is a simple test website</p> 
  </div>  
  <script src="script.js"></script>
</body>
</html>

Let's see how we can use element-only navigation to access the first child node of the body and its first element child node:

// Accessing the first child node of the bodylet firstChild = document.body.firstChild;console.log(firstChild); // #text // Accessing the first element child node of the bodylet firstElementChild = document.body.firstElementChild;console.log(firstElementChild); // <nav>

As you can see, the first child node of the body is a text node, while the first element child node is the nav element. Similarly, we can use the lastElementChild property to access the last element child node of the body:

// Accessing the last element child node of the bodylet lastElementChild = document.body.lastElementChild;console.log(lastElementChild); // <script>

Now, let's see how we can use this to change the style of our page. For example, to change the background color of the nav bar to red, we can define the following function:

const changeBgRed= () => {    document.body.firstElementChild.style.background = "red";}

Then, reload your web page, and you will see the style has been changed for the nav bar (which is the first child of the body).

Did you find this article valuable?

Support Arpan Mukherjee's Blogs by becoming a sponsor. Any amount is appreciated!