jqueryHow can I use jQuery to access data attributes?
jQuery provides a simple way to access data attributes using the .data()
method. This method takes the name of the data attribute as its argument and returns the value of the data attribute. The following example code block demonstrates how to access a data attribute called data-example
:
var example = $('#example').data('example');
console.log(example); // Output: 'This is an example'
The code above is composed of the following parts:
var example =
- This declares a variable calledexample
which will store the value of the data attribute.$('#example')
- This selects the element with the id ofexample
and stores it in a jQuery object..data('example')
- This accesses the data attribute calledexample
from the jQuery object.console.log(example)
- This prints the value of the data attribute to the console.
You can also use the .attr()
method to access data attributes. This method takes the name of the attribute as its argument, and returns the value of the attribute. The following example demonstrates how to access the data attribute using the .attr()
method:
var example = $('#example').attr('data-example');
console.log(example); // Output: 'This is an example'
For more information, please see the following links:
More of Jquery
- How do I use jQuery ZTree to create a hierarchical tree structure?
- 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 zoom in or out on an element?
- How do I use jQuery to change the z-index of an element?
- How do I use a jQuery zoom plugin?
- How do I use jQuery to zip files?
- How do I download a zip file using jQuery?
- How can I use jQuery to zoom an image when the user hovers over it?
- How do I use jQuery to zoom in on an image?
See more codes...