getElementsByTagName()

getElementsByTagName()

document.getElementsByTagName()方法返回指定标签名称的所有元素。
getElementsByTagName()的语法)方法如下:
 document.getElementsByTagName("name")
在这里,必须输入tag名称。

document.getElementsByTagName()方法的示例

在此示例中,我们将计算使用的段落总数在文档中。为此,我们调用了document.getElementsByTagName(" p")方法,该方法返回所有段落。
 <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>

以上示例的输出

This is h2 tag

This is h2 tag

This is h3 tag

This is h3 tag

This is h3 tag


注意:此页面上给定示例的输出可能有所不同,因为它将计算本文档中使用的para的总数,h2的总数和h3标记的总数。