This content originally appeared on Go Make Things and was authored by Go Make Things
Yesterday, we looked at how to get the first and last elements inside a parent. Today, we’re going to look at how to get the next and previous sibling elements.
Once again, we’re going to use some sample markup for today’s article.
<ul>
<!-- The gray wizard -->
<li>Gandalf</li>
<li>Radagast</li>
<li id="hermione">Hermione</li>
<!-- The surprise hero -->
<li>Neville</li>
</ul>
Let’s dig in!
The Node.nextSibling
and Node.previousSibling
properties
The Node.nextSibling
and Node.previousSibling
properties get the next and previous sibling node of an element, including nodes that aren’t elements (such as comments and text fragments).
let hermione = document.querySelector('#hermione');
// returns <!-- The surprise hero -->
let next = hermione.nextSibling;
// returns <li>Radagast</li>
let previous = hermione.previousSibling;
The Node.nextElementSibling
and Node.previousElementSibling
properties
The Node.nextElementSibling
and Node.previousElementSibling
properties work a lot like Node.nextSibling
and Node.previousSibling
, but they get the next and previous sibling that’s an element of the target element.
Looking at our example markup again, the nextElementSibling
property would get the list item (li
) with Neville
instead of the comment node.
let hermione = document.querySelector('#hermione');
// returns <li>Neville</li>
let next = hermione.nextElementSibling;
// returns <li>Radagast</li>
let previous = hermione.previousElementSibling;
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2021-05-12T14:30:00+00:00) How to get the next and previous sibling elements with vanilla JS. Retrieved from https://www.scien.cx/2021/05/12/how-to-get-the-next-and-previous-sibling-elements-with-vanilla-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.