HTML and CSS Reference
In-Depth Information
Accessing Custom Data Attributes Using JavaScript
Now that you know what custom data attributes are, let's see how to access them in JavaScript code.
Consider the JavaScript code shown in Listing 6-13, which illustrates how you can access the data-*
attributes used in Listing 6-12 using JavaScript code.
Listing 6-13. Accessing data-* Attributes in JavaScript Code
var emp = document.getElementById('emp1');
alert('Employee ID : ' + emp.getAttribute('data-employeeid'));
alert('Title : ' + emp.getAttribute('data-title'));
emp.setAttribute('data-employeeid', '100');
emp.setAttribute('data-title', 'Senior Manager');
alert('New Employee ID : ' + emp.getAttribute('data-employeeid'));
alert('New Title : ' + emp.getAttribute('data-title'));
This code uses the DOM document's getElementById() method to grab a table row with ID of emp1 . It
then retrieves the values of the data-employeeid and data-title custom data attributes using the table
DOM element's getAttribute() method. The values are displayed in an alert box. Further, the code
changes the values of data-employeeid and data-title using the setAttribute() method. The changed
values are also displayed in an alert box.
Although the technique of getting and setting data-* attributes from Listing 6-13 works as expected,
HTML5 offers a technique exclusively designed for accessing data-* attributes. HTML5 data-* attributes
are made available to your code through the dataset property of the underlying DOM element. Listing
6-14 shows how to use the dataset property to access data-* attributes.
Listing 6-14. Using the dataset Property to Access data-* Attributes
var emp = document.getElementById('emp1');
alert('Employee ID : ' + emp.dataset.employeeid);
alert('Title : ' + emp.dataset.title);
emp.dataset.employeeid = '200';
emp.dataset.title = 'Junior Manager';
alert('New Employee ID : ' + emp.dataset.employeeid);
alert('New Title : ' + emp.dataset.title);
To retrieve a data-* property value, you simply use the attribute name without data- against the
dataset property. Similarly, to set a data-* attribute value, you use its name against the dataset property
and assign a value to it.
If the custom data attribute contains a hyphen ( - ), you can access the attribute using camel casing.
For example, to access the data-employee-birthdate attribute, you use the following code:
alert('Employee ID : ' + emp.dataset.employeeBirthdate);
As you can see, the attribute name contains employee-birthdate . But when you access it using the
dataset property, it's referred to as employeeBirthdate .
Accessing Custom Data Attributes Using jQuery
The jQuery library also supports accessing custom data attributes by providing methods exclusively to
work with data-* attributes. Listing 6-15 shows how you can use jQuery to retrieve and assign data-*
attribute values.
Search WWH ::

Custom Search