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 can I use jQuery in WordPress?
- How do I use jQuery to zip files?
- How do I add a zoom feature to my website using jQuery?
- How do I use jQuery to zoom in or out on an element?
- How can I get the y position of an element using jQuery?
- How can I use JQuery with Yii2?
- How do I prevent XSS attacks when using jQuery?
- How do I use jQuery's noconflict mode?
- How do I create a jQuery Yes/No dialog?
See more codes...