js DOMのいくつかの一般的な方法

4802 ワード

 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     }