Friday, October 09, 2009

JQuery – Attribute Filters

JQuery attribute filters make it easy to select and modify particular attributes in your HTML DOM.

For example: if you wanted to hide all links in a page, here is what you need to do

$("a[href]").toggle();

But what if you need to hide only some of the links on your page?

Maybe the one that links to “http://www.ai.com/”

$("a[href='http://www.ai.com/']").toggle();

Maybe all the ones that have google in the href….

$("a[href*='google']").toggle();

(the key to above filter is the “*” – which matches anywhere in the attribute’s value)

Maybe all the ones that end with org

$("a[href$='org']").toggle();

(the key to the above filter is the “$” – which matches to the end of the attribute’s value)

Maybe all the ones that begin with http://doc

$("a[href^='http://docs']").toggle();

(here the the key is the “^” character – which matches only to the beginning of the attribute’s value)

Here are important points to remember:

  1. The filters are case sensitive. (I dont think there is a way to make them case-insensitive)
  2. Unlike regular RegEx expressions – you do not need to escape characters (such as “/” and “&”)
  3. This was true as of JQuery 1.3.2

No comments: