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 can I get the y position of an element using jQuery?
- How do I use jQuery with Yarn?
- How do I prevent XSS attacks when using jQuery?
- How do I use jQuery to detect window resize events?
- How do I use jQuery UI Dialog?
- How do I uncheck a checkbox using jQuery?
- How do I remove an attribute using jQuery?
- How can I convert a jQuery JSON object to an array?
- How do I use jQuery to zip files?
See more codes...