setAttribute()它允许我们对属性节点的值做出修改。与getAttribute一样,setAttribute也只能用于元素节点:
var shopping = document.getElementById("purchases");
shopping.setAttribute("title","a list of goods");
在下面的例子里,第一语句得到id为purchase的元素,第二条语句把这个元素的title属性值设置为a list of goods:
var shopping = document.getElementById("purchases");
alert(shopping.getAttribute("title"));
shopping.setAttribute("title", "a list goods");
alert(shopping.getAttribute("title"));
我们可以用getAttribute来证明这个元素的title属性值确实发生了变化:
var shopping = document.getElementById("purchases");
alert(shopping.getAttribute("title"));
shopping.setAttribute("title", "a list goods");
alert(shopping.getAttribute("title"));
加载页面后将填出两个alert对话框:第一个alert对话框出现在setAttribute被调用之前,它将是一篇空白或显示单词”null“;第二个出现在设置title属性之后,天将显示“a list of gods”消息。
在上例中,我们设置了一个节点的title属性,这个属性原先并不存在。这表明setAttribute实际完成了两项操作:先创建这个属性,然后设置它的值。如果setAttribute用在一个本身就有这个属性的元素节点上,这个属性值就会被覆盖掉。
在前面文章里提到的“购物清单”示例文档里,p元素已经有了一个title属性,这个属性的值是a gentle reminder。可以用setAtribute 来改变它的值:
var paras = document.getElementsByTagName("p");
for (var i =0; i < paras.length; i++) {
var title_text = paras[i].getAttribute("title");
if (title_text) {
paras[i].setAttribute("title", "brand new title text");
alert(paras[i].getAttribute("title"));
}
}
Related posts: