TOC
Need to learn JavaScript? jQuery is a JavaScript framework, so if you don't already know about the JavaScript programming language, we recommend that you learn it now: Learn JavaScript

The community is working on translating this tutorial into German, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Selectors:

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.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!