<script type="text/javascript"> function countpara(){ var totalpara=document.getElementsByTagName("p"); alert("total p tags are: "+totalpara.length); } </script> <p>This is a pragraph</p> <p>Here we are going to count total number of paragraphs by getElementByTagName() method.</p> <p>Let's see the simple example</p> <button onclick="countpara()">count paragraph</button>
以上示例的输出
This is a pragraph
Here we are going to count total number of paragraphs by getElementByTagName() method.
Let's see the simple example
document.getElementsByTagName()方法的另一个示例
在此示例中,我们将计算文档中使用的h2和h3标签的总数。
<script type="text/javascript"> function counth2(){ var totalh2=document.getElementsByTagName("h2"); alert("total h2 tags are: "+totalh2.length); } function counth3(){ var totalh3=document.getElementsByTagName("h3"); alert("total h3 tags are: "+totalh3.length); } </script> <h2>This is h2 tag</h2> <h2>This is h2 tag</h2> <h3>This is h3 tag</h3> <h3>This is h3 tag</h3> <h3>This is h3 tag</h3> <button onclick="counth2()">count h2</button> <button onclick="counth3()">count h3</button>