Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

<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?

like image 330
coderex Avatar asked Nov 27 '22 02:11

coderex


2 Answers

theDivElement.getElementsByTagName('a').length
like image 90
Fabien Ménager Avatar answered Dec 09 '22 18:12

Fabien Ménager


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>
like image 30
Dror Avatar answered Dec 09 '22 17:12

Dror