jqueryHow do I use the jQuery attr() method?
The jQuery attr()
method is used to get or set attributes and values of selected elements. It can be used to get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
Example code block:
<script>
$(document).ready(function(){
$("button").click(function(){
var text = $("p").attr("style");
alert(text);
});
});
</script>
<p style="color:red;">This is a paragraph.</p>
<button>Get Attribute</button>
Output example
color:red;
The code above contains the following parts:
$("button")
: This is a jQuery selector which selects the button element..click(function()
: This is a jQuery event handler which attaches a function to the click event of the button element.var text = $("p").attr("style")
: This is a jQuery method which gets the value of the style attribute of the paragraph element.alert(text)
: This is a JavaScript method which displays the value of the variabletext
in an alert box.
Helpful links
More of Jquery
- How can I get the y position of an element using jQuery?
- How can I use JQuery with Yii2?
- How do I use the jQuery masked input plugin?
- How do I uncheck a checkbox using jQuery?
- How can I convert jQuery code to vanilla JavaScript?
- How can I convert XML data to JSON using jQuery?
- How can I use jQuery to control the visibility of an element?
- How do I use the jQuery UI Datepicker?
- How do I use jQuery to trigger an event?
- How do I use jQuery to toggle an element?
See more codes...