一,getAttribute
getAtrribute是一个函数。它只有一个参数,即打算查询的属性的名字。
object.getAttribute(attribute);
getAtrribute方法不属于document对象,所以不能通过document对象调用。它只能通过元素节点对象调用。
例如,getELementsByTagName与getAttribute合用,获取每个
元素的title属性:
var paras = document.getElementsByTagName("p");
for(var i = 0; i<paras.length;i++){
alert(paras[i].getAttribute("title"));
}
二,setAttribute
setAttribute允许我们对属性节点的值作出修改,与getAttribute一样,setAttribute也只能用于元素节点。
object.setAttribute(attribute, value);
在下面的例子里,第一条语句的到id是purchase的元素,第二条语句把这个元素的title属性值设置为a list of foods。
var shopping = document.getElementById("purchase");
shopping.setAttribute("title", "a list of goods");
可以利用getAttribute来证明这个元素的title属性值确实发生了变化。
var shopping = document.getElementById("purchase");
alert(shopping.getAttribute("thitle"));
shopping.setAttribute("title", "a list of goods");
alert(shopping.getAttribute("title"));
加载页面后将会弹出两个alert对话框:第一个alert对话框出现在setAttribute被调用之前,它将是一片空白或显示单词“null“;第二个出现在设置title属性值之后,它将显示”a list of goods“消息。
在例子中,我们先设置了一个节点的title属性,这个属性原先并不存在。这表明setAttribute实际完成了两项操作:先创建这个属性,然后设置它的值,如果setAttribute用在一个本身就有这个属性的元素节点上,这个属性的值就会被覆盖掉。