Sunday, November 16, 2008

jQuery Select Notes

class: e.g. <p class="me"> text</p>
jQuery: $('.me')

id: e.g. <p id="me">text</p>
jQuery: $('#me')

element: e.g. <p>text</p>
jQuery: $('p')

elements inside id's: e.g. <ul id="me"><li><a>...
jQuery: $('#me a') will select all the anchor elements <a> under that <ul> tag.

elements inside elements (child tags): e.g. <html><p>text</p></html>
jQuery: $('body > p')

elements next to elements (siblings)
jQuery: $('p + div')

elements with attributes: e.g. <img src="..." alt="..." /> 
jQuery: $('img[alt]') will select all <img> tags with an alt attribute
$('a[href]') will select all anchor tags with an href attribute and thereby exclude named anchors: e.g. <a name="jumpToMyLocation">

elements with attributes having specific values
exact value: $('input[type=text]') will select all input tags with an attribute of type set to text.
starts with: $('a[href^=mailto:]') will select all anchor tags that have an href attribute set to a value that starts with 'mailto:'.
ends with: $('a[href$=html]') will select all anchor tags that have an href attribute set to a value that ends with '.html'.
contains: $('a[href*=content]') will select all anchor tags that have an href attribute set to a value that contains the text 'content'.

filter with : (colon)
$('tr:odd') will filter the <tr> selection from a table by the odd rows using a zero based index for the <tr> tags.
$('a:not([href$=html]') will filter the anchor selection by excluding all anchor tags with href attributes that end in 'html'.
$('li:has(a)') will filter the <li> selection by <li> elements that have <a> elements as child elements. This will result in a collection of <li> tags and not <a> tags.
$('a:contains(click here)') will filter the anchor tags which have the text 'click here'.
$('div:hidden') will get all the <div> tags that are hidden.
$('div:visible') opposite of $('div:hidden')

3 comments:

  1. See this in action:
    codylindley.com/.../jqueryselectors

    ReplyDelete
  2. Short and Straightforward, thanks!

    ReplyDelete