The Power of jQuery Selectors: Selecting by CSS Styles

In a similar fashion to CSS, if you want to select elements by class, use a dot (.). For example:

$(“p.highlighted”);

Up to now, you’ve selected elements using the format $(“element#id”), $(“element.class”), or something similar. It’s not actually necessary to precede any of these selectors with an element name followed by the filter. It’s just as valid to rewrite the previous examples like this:

$(“#stuffId”)

$(“.myCssClass”)

Because characters such as hash (#) have special meaning, if you want to use them in selection expressions, you’ll need to backslash escape those characters. The following list of characters all contain special meanings inside of selectors, and should be backslash escaped if you want to match against them:

# ; & , . + * ~ ‘ : “ ! ^ $ [] ( ) = > | /

For example, if you use the dollar sign as a naming convention for IDs in your HTML documents, you’d write an ID selector like this:

<!DOCTYPE html>

<html>

<head>

<script src=”http://code.jquery.com/jquery-1.7.1.js”>

</script>

<script>

var n = $”#\\$specialId”).length;

console.log(n);

</script>

</head>

<body>

<div id=”$specialId”>T-Rex</div>

</body>

</html>

Code snippet is from escaped-selectors.txt

The last two basic selectors in this section are the multiple selector and descendant selector. The descendant selector, which takes the form $(“ancestor descendant”), returns a wrapper object with the descendants of a specified ancestor. For example:

$(“form input”)

returns a wrapper with all of the inputs that are children of a form.

By no means are you limited to passing only a single selector expression. You can also combine different kinds of selectors, with a comma-delimited list of selectors:

$(“div#gallery, div#userInfo, form”);

Table 4-1 summarizes the basic selector types.

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

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