将某些数据设置为firstChild“数据ID”。魅力? [英] Set certain data to firstChild "data-id" attrbute?
问题描述
如何获取/设置firstChild的属性 data-id?
我可以设置文本区域的名称和内部文本:
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;
我想要做的就是这样更改数据ID值(伪代码):
what I am trying to do is to change "data-id' value like this (pseudocode):
el.firstChild.data('id')=j;
只需澄清一下-一点HTML:
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>
您
推荐答案
尝试此操作-
使用 firstElementChild
而不是 firstChild
此属性与<$ c $之间的区别c> firstChild ,即 firstChild
返回第一个子节点作为元素节点,文本节点或注释节点(取决于第一个),而 firstElementChild
返回第一个子节点作为 element节点(忽略文本和注释节点) 。
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/
数据集$ c
dom
的$ c>属性保存dom的所有数据属性的映射。
dataset
property of dom
holds a map of all data attributes of dom.
这篇关于将某些数据设置为firstChild“数据ID”。魅力?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!