js DOM的几个常用方法

 1
1 <div id="div1">这是个测试</div>
2 <p class="acc">111</p>
3 <p class="dd">222</p>

 

  //js DOM的几个常用方法
 2     //document.getElementById,  3     // document.getElementsByTagName,  4     // document.getElementsByClassName,  5     // getAttribute,  6     // setAttribute
 7 
 8     var div1 = document.getElementById("div1").innerHTML;  9     console.log(div1);//output:这是个测试
10 
11     var pars = document.getElementsByTagName("p"); 12     for (var i = 0; i < pars.length; i++) { 13         var title = pars[i].getAttribute("class"); 14         if (title) { 15             pars[i].setAttribute("class", "look");//修改class的值为look
16             console.log(pars[i].getAttribute("class"));//output:look
17  } 18  } 19 
20     var cls = document.getElementsByClassName("look"); 21     for (i in cls) { 22         console.log(cls[i].innerHTML);//111,222
23     }

 

你可能感兴趣的:(js DOM的几个常用方法)