给定一段超文本标记语言,我是否可以有选择地选择某些类型的元素(例如,输入)并使用JavaScript添加自定义属性?如果这个属性存在,我还需要删除它。
我以前使用过jQuery,但是我不能使用它来完成这个特定的任务。
发布于 2009-04-16 20:09:16
Accessing HTML attributes using the DOM
element.hasAttribute('foo');
element.getAttribute('foo');
element.setAttribute('foo', value);
element.removeAttribute('foo');
发布于 2021-01-01 22:49:32
<div class="first-div">
<p class="first-p">Hello!
</p>
</div>
通过javascript添加属性:
var myDiv= document.getElementsByClassName("first-div")[0];
var myp= myDiv.children[0];
nyp.setAttribute('myAttribute','valueForAttribute');
通过javascript获取属性:
console.log(myp.getAttribute('myAttribute'));
发布于 2009-04-16 19:56:37
el.attribute = value
这就是它的全部。如果该属性不存在,则创建该属性。
https://stackoverflow.com/questions/757799
复制相似问题