JavaScript – Get Previous Sibling of an HTML Element

To get the previous sibling of a specific HTML Element, using JavaScript, get reference to this HTML element, and read the previousElementSibling property of this HTML Element.

previousElementSibling property returns the element immediately prior to this HTML element.

Example

In the following example, we will get the previous sibling of the HTML Element, where the HTML element is selected by id "myElement". Once we get the previous sibling, we will change its color to red.

example.html

Try this html file online, and click on the Click Me button. The script gets the previous sibling of the HTML Element #myElement, and changes its color to red.

ADVERTISEMENT

Conclusion

In this JavaScript Tutorial, we learned how to get the previous sibling element of an HTML Element, using JavaScript.