Working with HTML Data Attribute using Jquery

Web Development Working with HTML Data Attribute using Jquery

jQuery Data Attribute Tutorial: A Step-by-Step Guide to Accessing and Modifying Data Attributes.

HTML example

<button type="button" data-id="1234" id="saveButton">Save</button>

Get Data Attribute Value

First option, use the data() method:

var id = $("#saveButton").data("id");

Second option, use the attr() method:

var id = $("#saveButton").attr("data-id");

Set Data Attribute on the fly

Using the data() method to update data does not affect attributes in the DOM. To set a data attribute value, use attr() method.

First option, use the data() method:

var id = $("#saveButton").data("id", "4321");

Second option, use the attr() method:

var id = $("#saveButton").attr("data-id", "4321");

Get Updated Data Attribute on the fly

If the value of the data attribute was changed on the fly using the data() method, use the data()metod to get the value of the data attribute:

var id = $("#saveButton").data("id");

If the value of the data attribute was changed on the fly using the attr() method, use the attr()metod to get the value of the data attribute:

var id = $("#saveButton").attr("data-id");

Find Data Attribute

<div id="dataWrap">
    <div data-id="1">Item 1</div>
    <div data-id="2">Item 2</div>
    <div data-id="3">Item 3</div>
    <div data-id="4">Item 4</div>
</div>

Selecting element by data attribute equal 3

var item = $('div[data-id="3"]');

Foreach Data Attribute

<span data-layout="main">Some random text</span>
<span data-layout="main">Some random text</span>
<span data-layout="main">Some random text</span>
<span data-layout="main">Some random text</span>

Find all elements with a certain data attribute

$('span[data-layout]').each(function() {
    console.log(this);
});

Find all elements with a certain data attribute value

$('span[data-layout="main"]').each(function() {
    console.log(this);
});