Find the next or previous siblings or the parent DOM element
In jQuery, you can find the next, previous, and parent element using the next()
, prev()
, parent()
and closest()
functions. The equivalents in JavaScript are nextElementSibling
, previousElementSibling
, parentElement
and closest
attributes.
Refer to the following code snippet to find the next, previous, and parent element through jQuery and vanilla JavaScript:
// Find the next, previous, and parent element using jQuery
$(".blog-post").next();
$(".blog-post").prev();
$(".blog-post").parent();
$(".blog-post").closest('.post-wrapper');
// Find the next, previous, and parent element using vanilla JavaScript
let blogPost = document.querySelector(".blog-post");
blogPost.nextElementSibling;
blogPost.previousElementSibling;
blogPost.parentElement;
blogPost.closest('.post-wrapper');