jQuery DOM Attributes tutorial

→ Are you a new visitor? Please visit the page guidance for new visitors ←

jQuery DOM Attributes

In the previous chapters we talked about jquery selectors and we learned that they are coming from css world. We selected elements that were available in the DOM that can be manipulated in all kinds of ways.

In this tutorial we will go further and we will talk about DOM attributes. We can manipulate properties and attributes assigned to DOM elements such as id, title, href or src. For these attributes, jquery come with a bunch of methods that are used to set, update, get or remove attributes that exist or not in the dom.

Let’s see a little bit what are we talking about. Imagine that we have the following DOM structure:

The “attr” method

In the above example, we setup an image with all kinds of attributes in the DOM. Now, we want to manipulate that attributes in different ways. Let’s say we want to get the id of the above image and store that into a variable. Do you remember the last tutorial about selectors (this one)? We want to select the id for this image, so we will do that like this:

First, we selected the image, and then called the method called “attr” on the selected tag, with a parameter called id as a string. Now, if we check our new variable for contents, we see that it has as a value of string, our id from the dom “theIdOfMyImage”.

IMPORTANT ! The above selector is matching all the images from the dom, so if you have more than one, you have to be more specific about the selector, otherwise the attr method will not work. 

As a homework for you, let’s say that you have to select the class of our image. I’ll spare you from the effort because I guess that you already know this one 🙂

The “removeAttr” method

Other than getting attributes, we can remove them as I told before. We do that with the following method.

 Other methods

.hasClass(‘className’); – This method returns true if the specified class is present on the selected element.

eg:

.removeClass(‘className’); – This is similar to removeAttr method but it is called for the class of the selected item.

.toggleClass(‘className’); – Adds the specified class if it is not present, and removes the specified class if it is present.

.html(); – This method if it is called without a parameter, it will get the HTML structure from the selected element.

eg:

If called with a parameter, it will set a html structure for the selected element.

.text(); – Get the combined text contents of all matched elements. Called with a string parameter, it will set the text contents of all matched elements.

.val(); – Get the input value of the selected element. Called with a string parameter, it will set the input value of all matched elements.

Summary

In this chapter, we learned how to manipulate DOM attributes through jquery methods. Stay tuned for the next chapter in which we will talk about DOM Traversing.

Request an article ←