Getting, Setting, and Removing DOM Element Attributes - J Query

You have selected a DOM element using the jQuery function and need to get or set the value of the DOM element’s attribute.


jQuery provides the attr() method for getting and setting attribute values. In the following code, we are going to be setting and then getting the value of an <a>element’s hrefattribute:

As you can see in the code example, we are selecting the only <a>element in the HTML document, setting its hrefattribute, and then getting its value with the same attr()method by passing the method the attribute name alone. Had there been multiple <a>elements in the document, the attr() method would access the first matched element.The code when loaded into a browser will alert() the value that we set for the hrefattribute.
Now, since most elements have more than one attribute available, it’s also possible to set multiple attribute values using a single attr() method. For example, we could also set the title attribute in the previous example by passing the attr() method an object instead of two string parameters:

With the ability to add attributes to elements also comes the ability to remove attributes and their values. The removeAttr() method can be used to remove attributes from HTML elements. To use this method, simply pass it a string value of the attribute you’d like to remove (e.g., jQuery('a')removeAttr('title')).

In addition to the attr() method, jQuery provides a very specific set of methods for working with the HTML element class attribute. Since the class attribute can contain several values (e.g., class="class1 class2 class3"), these unique attribute methods are used to manage these values.
These jQuery methods are as follows:

Updates the class attribute value with a new class/value including any classes that were already set

Checks the value of the class attribute for a specific class

Removes a unique class from the class attribute while keeping any values already set

Adds the specified class if it is not present; removes the specified class if it is present

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics