jQuery Attributes Basics

A previous article explained jQuery Selectors, the most important property of jQuery. This article explains jQuery Attributes. There are many important properties of DOM or HTML elements, like for the <img> tag the src, class, id, title and so on properties. jQuery provides ways to easily manipulate an element's attributes and gives us access to the element so that we can also change its properties.

attr() is a method to get the value of an attribute. Let's understand using an example as in the following:

attr

Here we will get the value of title for id= divid.

So the output will be:

Output will be

Using jQuery attributes we can set the value of other HTML tag elements.

Example: Here we are setting the src of the image element.

image element

Here the value of src will be replaced by “../images/jquery.jpg”.

Similarly we can use addClass(classes) to apply the defined style sheets onto all the matched elements.

addClass

The output for this code will be:

output

In a similar way I am writing some important methods as in the following. Do practice these and write to me about your experiences.

  1. attr( properties ) Set a key/value object as properties to all matched elements.
  2. attr( key, fn ) Set a single property to a computed value, on all matched elements.
  3. removeAttr( name ) Remove an attribute from each of the matched elements.
  4. hasClass( class ) Returns true if the specified class is present on at least one of the set of matched elements.
  5. removeClass( class ) Removes all or the specified class(es) from the set of matched elements.
  6. toggleClass( class ) Adds the specified class if it is not present, removes the specified class if it is present.
  7. html( ) Gets the HTML contents (innerHTML) of the first matched element.
  8. html( val ) Sets the HTML contents of every matched element.
  9. text( ) Gets the combined text contents of all matched elements.
  10. text( val ) Sets the text contents of all matched elements.
  11. val( ) Gets the input value of the first matched element.

Do practice these attribute methods and ping me if you have any problem. Keep coding.