JavaScript第三章:获取和设置属性

  根据上一节介绍的三种获得元素的方法,得到所需要的元素之后,我们可以设法获得它的各个属性。

   getAttribute()就是用来获得元素的属性,而setAttribute()可以修改属性节点的值。

1.getAttribute(attribute)

     getAttribute方法不属于document对象,只能通过元素节点对象调用。

object.getAttribute(attribute);
//获取每个<p>元素的title属性
//如果这个文本中有p元素,并且没有titl属性,这个方法调用会返回null值
var paras=document.getElementsByTagName("p");
for(var i=0;i<paras.length;i++){
    alert(paras[i].getAttribute("title");
  }

     

//修改脚本,让它在title有值时才弹出消息
var paras=document.getElementsByTagName("p");
for(var i=0;i<paras.length;i++){
    var title_text=paras[i].getAttribute("title");
    if(title_text){
       alert(title_text);
     }
    //if语句中title_text在逻辑上与title_text!=0是等价的
}

2.setAttribute(attribute,value)

    setAttribute()允许我们对属性做出修改。

    与getAttribute()相同,它只能用于元素节点。

    方法接受两个参数,第一个参数为属性名,第二个参数为给那个属性赋值的值。

    注意:通过setAttribute()方法对文档作出的修改不会反映在文档本身的源代码。(原因:DOM的工作模式是先加载文档的静态内容,再动态刷新,动态刷新不影响文档的静态内容。)DOM的威力也在于此,对页面内容进行刷新却不需要在浏览器里刷新页面。

object.setAttribute(attribute,value);
//设置原先不存在的属性
var shopping=document.getElementById("purchases");
alert(shopping.getAttribute("title"));
shopping.setAttribute("title","a list of goods");
alert(shopping.getAttribute("title"));

//加载页面后先后弹出两个窗口,首先弹出的窗口显示"null",后一个窗口显示"a list of goods"

//设置原先存在值的属性的值,原先的值将被新的值覆盖
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"));
        }
   }

猜你喜欢

转载自blog.csdn.net/rachel9798/article/details/82660134