无涯教程-JavaScript - getElementsByTagName

46 阅读1分钟

document.getElementsByTagName()方法返回指定标语法称的所有元素。

下面给出了getElementsByTagName()方法的语法:

document.getElementsByTagName("name")

在此,name为必填项。

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>这是一段</p> <p>在这里,无涯教程将通过getElementByTagName()方法计算段落总数。</p> <p>让无涯教程看一个简单的例子</p> <button onclick="countpara()">count paragraph</button>

上面例子的输出:

count paragraph

在这里,无涯教程将通过getElementByTagName()方法计算段落总数。

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>这是h2标签</h2>
<h2>这是h2标签</h2>
<h3>这是h3标签</h3>
<h3>这是h3标签</h3>
<h3>这是h3标签</h3>
<button onclick="counth2()">count h2</button>
<button onclick="counth3()">count h3</button>

上面例子的输出: 

这是h2标签

这是h2标签

这是h3标签

这是h3标签

这是h3标签

count h2 count h3

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

参考链接

www.learnfk.com/javascript/…