document.getElementsByTagName()方法返回指定标语法称的所有元素。
下面给出了getElementsByTagName()方法的语法:
document.getElementsByTagName("name")
在此,name为必填项。
在此示例中,无涯教程将计算文档中使用的段落总数。为此调用了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>
在这里,无涯教程将通过getElementByTagName()方法计算段落总数。
链接:https://www.learnfk.comhttps://www.learnfk.com/javascript/document-getElementsByTagName.html
来源:LearnFk无涯教程网
在此示例中,将计算文档中使用的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>
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)