Monday, July 11, 2016

jQuery Traversing and Filtering

DOM Traversing

The jQuery methods for traversing the DOM allow to access other element nodes relative to the initial selection.

jQuery methodmethod meaning
$('selector').find('selector2') all the elements in the current selection matching selector2
$('selector').closest('selector2') the nearest ancestral element matching selector2
$('selector').parent() the direct parent element of current selection
$('selector').parents() all the parents of current selection
$('selector').children() all the children of current selection
$('selector').next() next sibling of current element
$('selector').prev() previous sibling of current element

Example: DOM Traversing

Add, Remove and Test Elements in a Selection

Once a jQuery selection is made, more elements can be added or can be removed from it.

returned valuejQuery selector/method selector/method meaning
$selection $('selector1').add('selector2') add elements matching selector2: (selection1 ∪ selection2)
$selection $('selector1').filter('selector2') reduce the elements to those matching selector2: (selection1 ∩ selection2)
$selection $('selector1:not(selector2)')
$('selector1').not('selector2')
select elements that do not match selector2: (selection1 - selection2)
$selection $('selector1:has(selector)')
$('selector1').has('selector2')
select elements that have descendants matching selector2
$selection $('selector1:contains("text")') select elements that contain the text specified, (matching is case sensitive)
boolean $('selector1').is('selector2') check whether the current selection has an element matching a condition

Example: filter, traverse and test

Example: test elements with is(':contains()')

See the Pen jQuery selection filtering by Massimiliano (@maxdesimone) on CodePen.

Finding Elements in a Selection by Order

A jQuery selection is an array-like object, this let you select elements with methods and selector using index numbers

jQuery selector/method selector/method meaning
$selection = $('selector:eq(index)')
$selection = $('selector').eq(index)
select elements with index matching the index specified
$selection = $('selector:lt(index)') select elements with index less than the index specified
$selection = $('selector:gt(index)') select elements with index greater than the index specified

Example

No comments :

Post a Comment