Attribute filters

Attributes are those additional properties found inside HTML tags that allow the tag to refine itself. You're probably most familiar with the id and class attributes as well as the src attributes for img and script tags and of course the href attribute for a tags.

Attributes are powerful properties for defining and refining HTML elements, so you can imagine how powerful being able to filter using them can be. Powerful yes, but do keep in mind the simplest and the most direct approach to selecting items into the jQuery wrapper is often the best. My examples will show different class selections because they create nice visual examples, but in reality, you're better off using regular selectors to target class items and saving attribute filters for your more refined, tricky work.

You'll note that these filters differ from the other filters. Instead of : (colon marks), these filters use [] (square brackets). This means you can easily see in your selector syntax if you're filtering for an attribute. You'll also note that for every attribute out there in HTML's DOM, you can filter for it. There's no standard set of "attribute filter names"; you simply use the square brackets to indicate whatever attribute you want to filter for. You can even structure your attribute filter in a few ways:

Example

Syntax

Description

[attribute] [attribute=value] [attribute!=value] [attributeA=value]

[attribute$=value]

[attribute*=value]

Query("div [href]") css("background", "#f60");

Query("div [class='entry' ]" css("background", "#f60");

Query("div [class!='entry'] css("background", "#f60");

Query("div [href^='http://'; css("background", "#f60");

Query("div [href$='/']") css("background", "#f60");

jQuery("div [href*='page_ id']").css("background", "#f60");

Filters for an attribute, regardless of its value

Filters for an attribute and an exact specified value

Filters for attributes that do not have a specified value

Filters for attributes that have a value that begins with a specific string

Filters for attributes that have a value that ends with a specific string

Filters for attributes that contain a string

Here, we can take a look at targeting only the local links in our sidebar with the following jQuery code:

jQuery(".widget-area [href*='http://localhost']").css("background", "#f60");

The following screenshot shows the result, and only localhost links referencing the WordPress installation are highlighted:

Blogging For Business

Blogging For Business

Download this Guide And Discover How Start And Run Your Very Own Successful Business Blog. Always Wanted To Start Your Own Blog?

Get My Free Ebook


Post a comment