0

How can I get/set the firstChild's attribute "data-id"? I can set name and inner text of a textarea :

el.firstChild.name='txt_'+j;
el.firstChild.innerText = 'Textarea '+j;

what I am trying to do is to change "data-id' value like this (pseudocode):

el.firstChild.data('id')=j; 

Just to clarify - a bit of HTML:

<div id="5" class="textarea_cloned">
<textarea name="txt_5">Textarea 5</textarea>
<div class="remove" data-id="5"> X </div>
</div>

Thank you

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Rossitten
  • 1,140
  • 1
  • 16
  • 34
  • Data values cannot be changed by default, even though you can, it will not retrieve the value. Treating `data-id` as an attribute, though, can change its value –  Dec 17 '16 at 06:34
  • Please [use the search](http://stackoverflow.com/search?q=%5Bjavascript%5D+%5Bdom%5D+set+data+attribute): [Set data attribute using JavaScript](http://stackoverflow.com/q/11286661/218196) – Felix Kling Dec 17 '16 at 06:58
  • @Felix, I did...always do so, sire. I've just checked the search results and was unable to find the info guys have provided here. – Rossitten Dec 17 '16 at 07:03

2 Answers2

3

Try This-

Use firstElementChild instead of firstChild

The difference between this property and firstChild, is that firstChild returns the first child node as an element node, a text node or a comment node (depending on which one's first), while firstElementChild returns the first child node as an element node (ignores text and comment nodes).

 el.firstElementChild.dataset.id=j

DEMO

https://jsfiddle.net/vikrant47/frcqb42q/

dataset property of dom holds a map of all data attributes of dom.

vikrant singh
  • 2,091
  • 1
  • 12
  • 16
2

If you want to reflect it in HTML code then use setAttribute method to set an attribute. Although you need to use firstElementChild to get the element otherwise the textNode (whitespace at the beginning) may get as firstChild.

 el.firstElementChild.setAttribute('data-id', j)

var j = 10,
  el = document.getElementById('5');
el.firstElementChild.setAttribute('data-id', j)

console.log(el.innerHTML)
<div id="5" class="textarea_cloned">
  <textarea name="txt_5">Textarea 5</textarea>
  <div class="remove" data-id="5">X</div>
</div>

If you just want to add in dataset property then set the property in dataset.

el.firstElementChild.dataset.id = j
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188