jQuery Attr Attribute

The jQuery attr() attribute is used to return or set the attribute and its value to the selected element. It returns the attribute value of the first matched element. But we can set one or more than one attribute value pairs to the set of selected element. To return the value of each element individually, use the jquery loop.

Syntax Description
$(selector).attr(attribute) It gets an attribute's value.
$(selector).attr(attribute,value) To set an attribute and it's value.
$(selector).attr(attribute,function(index,currentvalue)) To set an attribute and it's value by using a function.
$(selector).attr({attribute:value, attribute:value,...}) To set multiple attributes and values.

The selector is the element on which class to be added.

attr() Examples

$(selector).attr(attribute)

<p class="cls1" id="demo"> Hello World!</p>
<script>
$(document).ready(function(){
   alert($("#demo").attr("class"));
});
</script>

 

$(selector).attr(attribute,value)

<style>.cls {color: red; }</style>
<p id="demo"> Hello World!</p>
<script>
$(document).ready(function(){
   $("p#demo").attr('class', 'cls');
});
</script>

Output of the above code

Hello World!

 

$(selector).attr(attribute, function(index,currentvalue))

<style>.cls1 {color: green; }</style>
<p id="txt"> Hello World!</p>
<script>
$(document).ready(function(){
$("p#txt").attr("class", function(index) {
return "cls1";
})
});
</script>

Output of the above code

Hello World!

 

$(selector).attr(attribute, function(index,currentvalue))

<style>.cls3 {border: 5px solid green; } </style>
<img id="animal"/>
<script>
$(document).ready(function(){
$("img#animal").attr({'class' : 'cl3', 'src' : 'images/rabbit.jpg', 'alt' : 'rabbit' });
});
</script>

Output of the above code

rabbit

Read more articles


General Knowledge



Learn Popular Language