简体   繁体   中英

How to count the number of anchor tags within a div using javascript?

I want to know how to count the number of anchor tags present within a div element. eg:

<div>
<a href="1" >1</a>
<a href="2" >2</a>
<a href="3" >3</a>
<a href="4" >4</a>
</div>

How many <a> tags?

theDivElement.getElementsByTagName('a').length

Use HTML DOM getElementsByTagName() to get all "a" tags under an object.
To get the div you'de be better off giving it an ID and then use getElementsByTagName .

 var anchors = document.getElementById("thediv").getElementsByTagName("a"); alert("The Div has " + anchors.length + " links in it"); 
 <div id="thediv"> <a href="#">link 1</a> <a href="#">link 2</a> <a href="#">link 3</a> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM