HTML Dog
Skip to navigation

jQuery: DOM API

Selecting elements and interacting with the DOM are things you’ll probably use jQuery for the most. Luckily it’s really easy to do because the syntax for choosing an element, or set of elements, is exactly the same as element selection in CSS.

jQuery also makes performing actions on many elements at the same time simple, which is incredibly useful.

In the example below $('.note') selects all the elements with a class of note on the page and then we set the background of all of the note boxes to red and their heights to 100px.


$('.note').css('background', 'red').height(100);

jQuery uses a really neat chainable syntax that allows code like the above. This works because, for any kind of “setting” method, jQuery returns the same thing as the selector function (“$”) does: $ is a function that returns a jQuery wrapper around an element. .css is a method of that jQuery wrapper and it too returns the same wrapper. .height sets the height (duh) of the element selected, and of course there’s an equivalent for width.

Getters and setters

In the above example we used .css and .height to set the value of the element but these methods are also getters. Calling .height without any value returns the current element’s height and calling .css with just a CSS property name retrieves the property’s value.


var currentHeight = $('.note').height(),
    currentColor = $('.note').css('color');

If you’ve got more than one element selected (you have lots of note elements, say) a getter will retrieve the value for the first of them.

Context

It’s sometimes useful to limit the area of the DOM from which an element can be selected. The area of the DOM used is also known as a different context.

To tell jQuery which area you want to select from you pass a second argument that can be a DOM element, a string selector (selecting an element that jQuery will find and use) or a jQuery object. jQuery will only search within this context for your selector.

Here’s an example. Notice that the variables that are used to store jQuery objects begin with a dollar. This a convention to help you and readers of your code understand that it’s a jQuery object being saved.


var $header = $('header'),
    $headerBoxes = $('.note', $header);