How to Use the nextElementSibling Property in JavaScript?

Estimated read time 1 min read

The nextElementSibling property in JavaScript is used to access the next sibling element of a specified element in the DOM (Document Object Model). This property can be used to manipulate the content and style of the next sibling element.

Here is an example to illustrate how the nextElementSibling property can be used:

<p id="first">This is the first paragraph.</p>
<p id="second">This is the second paragraph.</p>

<script>
  let firstParagraph = document.getElementById("first");
  let secondParagraph = firstParagraph.nextElementSibling;

  secondParagraph.style.color = "blue";
  secondParagraph.innerHTML = "The text color has been changed to blue.";
</script>

In the above example, we use the getElementById method to select the first paragraph element, and then use the nextElementSibling property to access the second paragraph element. Finally, we change the text color of the second paragraph to blue and update its content.

Note that nextElementSibling only returns the next sibling element, not the next sibling node. If the next sibling node is not an element, it will return null.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply