首页 > 技术文章 > 设置属性节点(setAttribute())

zzq919101 2016-10-31 20:06 原文

setAttribute():方法将为给定元素节点添加一个新的属性值或是改变它的现有属性值:

element.setAttribute(attriibuteName,attributeValue);

属性的名字和值必须以字符串的形式传递给此方法,如果这个属性已经存在,它的值将被刷新,如果不存在,setAttribute()方法只能用在属性节点上。

在下例中,setAttribute()方法将把一个取值为“this is important” 的title属性添加到id属性值是fineprint元素上:

var message = document.getElementById("fineprint");
message.setAttribute("title","this is importanr");

不管“fineprint”的元素以前有没有title属性,他现在将有一个取值为this is important 的title属性。

即使某个元素还没有被插到文档树上,setAttribute()方法也可以设置在它的属性节点上,如果用createElement()方法创建了一个新元素,你可以在把它添加到文档树上之前对他的属性进行设置:

var para = document.createElement("p");
para.setAttribute("id","fineprint");
var container = document.getElementById("content");
container.appendChild(para);

DOM还提供了一个与setAttribute()方法作用刚好相反的getAttribute()方法,后者可以用来检索某个属性值。

推荐阅读