Jquery Traversing?
In this tutorial will discuss about jquery traversal specially, Sibling Element Traversal. Traversing means to reach to the particular element present in DOM Tree
Parent Element Traversal
Child Element Traversal
Sibling Element Traversal
Parent Element Traversal
- parent(): It returns the direct parent element of the selected element.
- parents(): It returns all ancestor elements of the selected element.
- parentsUntil(): It returns all ancestor elements between two given arguments.
Child Element Traversal
- children(): It returns all direct children of the selected element.
- find(): It returns descendant elements of the selected element.
Sibling Element Traversal
- siblings() : It returns all sibling elements of the selected element
- next() : It returns the next sibling element of the selected element.
- nextAll(): It returns all next sibling elements of the selected element
- nextUntil(): It returns all next sibling elements between two given arguments
- prev: It returns the previous sibling element of the selected element
- prevAll(): It returns all previous sibling elements of the selected element
- prevUntil(): It returns all previous sibling elements between two given arguments
# Example
Replace your html code with below code
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="jquery-3.2.1.min.js"></script> <style> .ancestor * { display: block; padding: 10px; margin: 10px; border: 2px solid gray; } </style> <script> $(document).ready(function () { //$("h2").siblings().css({ "border": "2px solid red" }) //$("h2").next().css({ "border": "2px solid red" }) // $("h2").nextAll().css({ "border": "2px solid red" }) //$("h2").nextUntil("h4").css({ "border": "2px solid red" }) //$("h2").prev().css({ "border": "2px solid red" }) //$("h2").prevAll().css({ "border": "2px solid red" }) $("h2").prevUntil("span").css({ "border": "2px solid red" }) }) </script> </head> <body> <div class="ancestor"> <p>Paragraph1</p> <span>span1</span> <h1>h1</h1> <h2 style="background-color:gray">h2</h2> <h3>h3</h3> <h4>h4</h4> <p>paragraph2</p> <span>span2</span> </div> </body> </html>