的document.getElementsByTagName()方法返回所有指定标签名称的元件。
所述的getElementsByTagName()方法的语法给出如下:
document.getElementsByTagName("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>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
count paragraph
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
count h2
count h3
评论前必须登录!
注册