No matter which type of selector we want to use in jQuery – be it CSS, XPath, or custom – we always start with the dollar sign and parentheses: $()
$() Factory Function
Let’s see some more common examples:
A tag name: $(‘p’) gets all paragraphs in the document.
An ID: $(‘#some-id’) gets the single element in the document that has the corresponding some-id ID.
A class: $(‘.some-class’) gets all elements in the document that have a class of some-class.
CSS Selectors
Chile combinator
>

$(‘#selected-id > li’)

Find each liste item (li) that is a child (>) of an element with an ID of selected-id (#selected-id).
Negation pseudo-class
not

$(‘#selected-id > li:not(.horizontal)’)

Find each list item that do not have a class of horizontal, which is a child of #selected-id.


XPath Selectors

$(‘a[@title]’)

This is a attribute selector, so use @ symbol inside square brackets. Example means that to select all links that have a title attribute.
Here are more examples about XPath Selectors.
Attribute selectors accept regular-expression-like syntax for identifying the beginning(^) or ending($) of a string. And also take an asterisk(*) to indicate an arbitrary position within a string.

$(‘a[@href^=”mailto:”]’)

href attribute begins with mailto

$(‘a[@href$=”.pdf”]’)

href attribute ends with .pdf.

$(‘a[@href*=”mysite.com”]’)

href attribute has mysite.com inside.
Custom Selectors
I just put some sample here.

$(‘tr:odd’)
$(‘tr:even’)
$(‘td:contains(“David”)’)
$(‘th’).parent()
$(‘tr:not([th]):even’)
$(‘tr:not[ht]:odd’)

The most recommended complicated way.

$(‘td:contains(“David”)’).parent().find(‘td:eq(1)’).addClass(‘highlight’).end().find(‘td:eq(2)’).addClass(‘highlight’);

David Yin

David is a blogger, geek, and web developer — founder of FreeInOutBoard.com. If you like his post, you can say thank you here

Leave a Reply

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