Skip to content Skip to sidebar Skip to footer

Set Certain Data To Firstchild "data-id" Attrbute?

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

Solution 1:

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.

Solution 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)
<divid="5"class="textarea_cloned"><textareaname="txt_5">Textarea 5</textarea><divclass="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

Post a Comment for "Set Certain Data To Firstchild "data-id" Attrbute?"