jQuery Tutorials

Overview

jQuery traversing, which means “to travel or pass across, over, or through”, are used to find HTML elements based on their relation to other page elements. It’s kind of like another form of jQuery selectors.

The following are some quick examples of traversing methods. A complete list of traversing methods can be found here along with more detailed descriptions of their intended use and syntax.

children() Method

The children() method returns all direct children of the selected element.

// searches for all children of a ul tag and applies CSS
$('ul').children().css({'color': 'red'});

closest() Method

The closest() method returns the first ancestor of the selected element.

// searches for the first ancestor of a div that is a ul tag and applies CSS
$('div').closest('ul').css({'color': 'red'});

first() Method

The first() method returns the first element of the selected elements.

// returns the first paragraph in a div and applies CSS
$('div p').first().css('color', 'red');

last() Method

The last() method returns the last element of the selected elements.

// returns the last paragraph in a div and applies CSS
$('div p').last().css('color', 'red');

not() Method

The not() method returns elements that do NOT match a certain criteria. Elements that DO match are removed.

// finds paragraphs that do NOT have a class of .third and applies CSS
$('p').not('.third').css('color', 'red');

parent() Method

The parent() method returns the direct parent element of the selected element.

// finds the parent of paragraph elements and applies CSS
$('p').parent().css({'color': 'red'});

siblings() Method

The siblings() method returns all sibling elements of the selected element.

// finds ALL siblings of a p element and applies CSS
$('p').siblings().css({'color': 'red'});

jQuery Notes:

  • To use jQuery on your site, it must first be downloaded from the official jQuery site and linked to in your document <head>, or linked to via a CDN in your document <head>
  • It is generally good practice to place your jQuery code/function inside the document load function so that the action takes place ONLY after the document has finished loading
  • When using jQuery, single or double quotation marks are acceptable and work identically to one another; choose whichever you prefer, and stay consistent

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.