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 variabletextin 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 can I use jQuery to check if an element is visible?
- How can I get the y position of an element using jQuery?
- How do I download a zip file using jQuery?
- How do I add a zoom feature to my website using jQuery?
- How do I use jQuery to zoom an image when it is clicked?
- How do I use jQuery to change the z-index of an element?
- How do I use jQuery to zoom in on an image?
- How do I use jQuery to zoom in or out on an element?
See more codes...