Cover Image for jQuery attr() method
98 views

jQuery attr() method

The jQuery attr() method is used to get or set attributes of HTML elements. It allows you to retrieve the value of an attribute or set a new value for the attribute on the selected elements.

The syntax for using the attr() method is as follows:

To Get Attribute Value:

$(selector).attr(attributeName);

To Set Attribute Value:

$(selector).attr(attributeName, value);
  • selector: It is a string that specifies the elements to be selected.
  • attributeName: It is a string representing the name of the attribute you want to get or set.
  • value (optional): It is the value that you want to set for the attribute.

Here’s an example of how you can use the attr() method:

HTML:

<img id="myImage" src="image.jpg" alt="My Image">

JavaScript:

// Get the value of the "src" attribute of the image
var src = $('#myImage').attr('src');
console.log('Image Source: ' + src);

// Set a new value for the "alt" attribute of the image
$('#myImage').attr('alt', 'New Image Alt Text');

In the above example, the attr() method is used to get the value of the “src” attribute of the image element with the ID “myImage” and log it to the console. Then, the attr() method is used again to set a new value for the “alt” attribute of the same image.

After using the attr() method to set the new value, the resulting HTML would look like this:

<img id="myImage" src="image.jpg" alt="New Image Alt Text">

The attr() method can be used with various attributes, including standard HTML attributes like src, alt, href, class, etc., as well as custom attributes that you add to your elements.

When using attr() to set an attribute value, it will update the attribute on all matched elements. If you only want to modify the attribute on the first element in the selected set, you can use the eq() method or index the selection.

If you want to remove an attribute from an element, you can pass null or an empty string as the value:

// Remove the "alt" attribute from the image
$('#myImage').attr('alt', '');

In the above example, the “alt” attribute will be removed from the image element.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS