JQuery

Jquery Traversal

jQuery Traversal: Navigating the DOM

What is Traversal?

  • Traversal means moving through the HTML structure.

  • It helps you find elements relative to others — parents, children, siblings, ancestors, descendants, etc.


Common jQuery Traversal Methods

Method Description Example
.parent() Selects immediate parent of element $('#item').parent()
.parents() Selects all ancestors $('#item').parents('div')
.children() Selects immediate children $('#list').children('li')
.find() Selects all descendants matching selector $('#list').find('a')
.siblings() Selects all siblings (same parent) $('#item').siblings()
.next() Selects immediate next sibling $('#item').next()
.nextAll() Selects all next siblings $('#item').nextAll()
.prev() Selects immediate previous sibling $('#item').prev()
.prevAll() Selects all previous siblings $('#item').prevAll()
.closest() Selects closest ancestor matching selector $('#item').closest('div')

Examples

1. Get the parent of an element

js
$('#myParagraph').parent().css('border', '2px solid blue');

2. Find all links inside a list

js
$('#myList').find('a').css('color', 'red');

3. Get all siblings of a selected item

js
$('#item2').siblings().hide();

4. Select the next sibling and change text

js
$('#item1').next().text('Changed next item');

5. Get the closest ancestor with a specific class

js
$('#button').closest('.container').css('background', '#eee');

Why Traversal Is Useful

  • Manipulate elements relative to user interaction.

  • Efficiently target elements without adding extra IDs or classes.

  • Traverse up, down, and sideways in the DOM tree.

Leave a Reply

Your email address will not be published. Required fields are marked *