add val in data-id jquery

Adding Val in Data-id jQuery

In jQuery, the .attr() method is used to get or set the value of an attribute of the selected element. To add a data-id attribute with a value to a div element using jQuery, we can use the following code:


$('div').attr('data-id', 'val');

This line of code selects all div elements on the page and adds a data-id attribute with a value of 'val' to each of them.

If we want to add a unique data-id value to each div element based on some condition, we can use a loop and generate the value dynamically. For example, suppose we have a list of items and we want to add a data-id attribute with a unique value to each item's div element:


var items = ['item1', 'item2', 'item3'];
$.each(items, function(i, val) {
  $('div.item').eq(i).attr('data-id', val);
});

This code first creates an array of items, then uses the $.each() method to iterate through the array and add a data-id attribute with a unique value to each corresponding div element with the class 'item'.

Alternatively, we can also use the .data() method to set a data attribute on an element:


$('div').data('id', 'val');

This line of code sets a data attribute called 'id' with a value of 'val' on all div elements on the page. The .data() method is a more efficient way to set data attributes, as it does not modify the HTML attribute and can also store more complex data types.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe