Using elements, ID’s and classes


The #id selector

A very common selector type is the ID based, which we saw in the “Hello, world” example. It uses the ID attribute of a HTML tag to locate the desired element. An ID should be unique, so you should only use this selector when you wish to locate a single, unique element. To locate an element with a specific ID, write a hash character, followed by the ID of the element you wish to locate, like this:

$("#divTest")

An example of it in use:

<div id="divTest"></div>
<script type="text/javascript">
$(function()
{
        $("#divTest").text("Test");
});
</script>

Now, while there is only a single element that matches our query above, you should be aware that the result is a list, meaning that it can contain more than one element, if the query matches more than one. A common example of this is to match all elements which uses one or several CSS classes.

The .class selector

Elements with a specific class can be matched by writing a . character followed by the name of the class. Here is an example:

<ul>
        <li class="bold">Test 1</li>
        <li>Test 2</li>
        <li class="bold">Test 3</li>
</ul>
<script type="text/javascript">
$(function()
{
        $(".bold").css("font-weight", "bold");
});
</script>

The element selector

You can also match elements based on their tag names. For instance, you can match all links on a page like this:

$(“a”)

Or all div tags like this:

$(“div”)

If you use a multi-element selector, like the class selector we used in the previous example, and we know that we’re looking for elements of a specific type, it’s good practice to specify the element type before the selector. Not only is it more precise, it’s also faster for jQuery to process, resulting in more responsive sites. Here is a re-written version of the previous example, where we use this method:

$("span.bold").css("font-weight", "bold");

This will match all span elements with “bold” as the class. Of course, it can be used with ID’s and pretty much all of the other selectors as well.

Selectors can do much more for you though. Read on for more cool examples.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s