Cover Image for previousElementSibling Property in javascript
168 views

previousElementSibling Property in javascript

The previousElementSibling property in JavaScript is a read-only property that returns the element immediately preceding the specified element in the document’s DOM tree, skipping any non-element nodes (such as text nodes or comments). It allows you to access the sibling element that comes before a particular element.

Here’s an example to illustrate the usage of previousElementSibling:

JavaScript
<ul>
  <li>Item 1</li>
  <li id="target">Item 2</li>
  <li>Item 3</li>
</ul>
JavaScript
const targetElement = document.getElementById('target');
const previousElement = targetElement.previousElementSibling;

console.log(previousElement.textContent); // Output: "Item 1"

In this example, we have an unordered list (ul) with three list items (li). We select the element with the id "target" using getElementById(). Then, we use the previousElementSibling property to access the previous sibling element, which is the first list item (<li>Item 1</li>). Finally, we log the text content of the previous element to the console.

It’s important to note that the previousElementSibling property only returns the immediate preceding sibling element. If there are non-element nodes (like text nodes or comments) between the target element and its previous sibling, they will be skipped, and the property will return the next preceding element.

If there is no previous element sibling, the previousElementSibling property will return null.

Make sure to use previousElementSibling when you specifically want to access element nodes and not other types of nodes in the DOM tree.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS