jQuery attr() Method - CodingTag
×


jQuery attr()

1333

  • This jQuery method is used to fetch and set the attributes and their values of the selected HTML elements.
  • It returns the specific attribute value of the first matched HTML element from the selected elements. On the other hand it set the value of the specific attribute of the all selected elements.

Related Topics:

jQuery detach
jQuery scrollTop

jQuery attr

Syntax:

This method has four different signatures which used to work for different tasks:

$(selector).attr(attribute);

This syntax is used to get the attribute value of the selected element.

Parameter description:

  • attribute: This parameter represents the attribute name which value you want to return by this method. It is mandatory.
  • $(selector).attr("attribute","value");

    The given syntax of attr() method is used to set the value of the of the attribute of the selected HTML element.

    Parameter description:

  • attribute: This parameter represents the attribute name of the selected element which value you want to set by this method. It is mandatory.
  • value: This parameter represents the new value of the specified attribute of the selected element. It is also required.
$(selector).attr("attribute",function(index, currentvalue)) ;

This syntax is also used to set the value of the specified attribute of the selected element by using a user defined function.

Parameter description:

  • function(index,currentvalue): This represents a user defined function which return the new attribute value of the selected HTML element.
  • index: This parameter is used to get the index position of the element in the set.
  • currentcontent: This parameter is used to return the current attribute value of the selected element.
$(selector).attr({"attribute":"value", " attribute ":"value", ...})

The above signature of the attr() method is used to set the multiple attributes value of the selected element.

Example:

In this example we get the title attribute value of a paragraph.

<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
.para{
background:pink;
padding:20px;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$data=$("p").attr('title');
alert($data);
});
});
</script>
</head>
<body>

<h2> jQuery attr() Method Example </h2>
<p class="para" title="hey!! welcome to CodingTag."> This is a paragraph </p>
<button> click me! </button>

</body>
</html>

Output:

When you click the button,



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments