Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set data-id attribute

Tags:

javascript

I am trying to set the data-id and/or value of a span from my js file after a click event.

<span id="test"></span>

my sudo code js file

nextLink: function(event) {
    $('#test').val = 3;
    $('#test').data('id') = 'Next';
},
like image 992
myTD Avatar asked Oct 24 '12 17:10

myTD


People also ask

What is data ID attribute?

The data-reactid attribute is a custom attribute that react can easily identify its components within the DOM. Just like the HTML “classes” and “id” attributes, “data-reactid” helps in uniquely identifying the element .

How do I select an element by data ID?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.

How do I find my data ID?

You can simply use the jQuery attr() method to find the data-id attribute of an HTML element.


2 Answers

Try setting it as an attribute..

 $('#test').attr('data-id' , 'Next');   // JQuery

You can also try the setAttribute() ..

var d = document.getElementById("test");  //   Javascript
d.setAttribute('data-id' , 'Next');       //

Using this approach will reflect the new attribute in the DOM

In your code You are trying to set the attribute which is not present .. So you need to add the attribute first to add that ..

like image 118
Sushanth -- Avatar answered Oct 14 '22 08:10

Sushanth --


You probably need this:

$('#test').data('id', 'Next');
like image 4
rinat.io Avatar answered Oct 14 '22 10:10

rinat.io