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 do I use jQuery ZTree to create a hierarchical tree structure?
- How do I use jQuery to zip files?
- How do I use jQuery to detect window resize events?
- How do I use jQuery to zoom in or out on an element?
- How do I download a zip file using jQuery?
- How can I use JQuery with Yii2?
- How can I get the y position of an element using jQuery?
- How can I use jQuery to check if an element is visible?
- How do I use a jQuery UI Slider?
- How do I use jQuery with Yarn?
See more codes...