Set data attribute using JavaScript

I am using DynaTree (https://code.google.com/p/dynatree), but I am having some problems and hope someone can help.

I show the tree on the page as below:

<div id="tree"> <ul> <li class="folder">Outputs <ul> <li id="item1" data="icon: 'base.gif', url: 'page1.htm', target: 'AccessPage'">Item 1 Title <li id="item2" data="icon: 'base.gif', url: 'page2.htm', target: 'AccessPage'">Item 2 Title <li id="item3" data="icon: 'base.gif', url: 'page3.htm', target: 'AccessPage'">Item 3 Title <li id="item4" data="icon: 'base.gif', url: 'page4.htm', target: 'AccessPage'">Item 4 Title </ul> </ul> </div> 

However, I am trying to change the icon on an element whether it is selected or not just using JavaScript .

the new icon I want to use is base2.gif

I tried using the following, but this does not work:

 document.getElementById('item1').data = "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'"; 

Does anyone know what I can do wrong?

+61
javascript dom dynatree
Jul 02 2018-12-12T00:
source share
2 answers

Use the setAttribute method:

 document.getElementById('item1').setAttribute('data', "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'"); 

But you really should use the data following the dash and with your property, for example:

 <li ... data-icon="base.gif" ...> 

And for this in JS use the dataset property:

 document.getElementById('item1').dataset.icon = "base.gif"; 
+135
Jul 02 2018-12-12T00:
source share

Please use the data set.

 var article = document.querySelector('#electriccars'), data = article.dataset; // data.columns -> "3" // data.indexnumber -> "12314" // data.parent -> "cars" 

so in your case to set the data:

 getElementById('item1').dataset.icon = "base2.gif"; 
+37
May 7 '14 at 10:34
source share



All Articles