Skip to content
the poor coder

add val in data-id jquery

Poor Man
Published
Reading time
1 min read

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:

Text

$('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:

Text

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:

Text

$('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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC