Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count all <a> on html page

I want to get all the <a> tags from an Html page with this JavaScript method:

function() {
    var links = document.getElementsByTagName('a');
    var i=0;
    for (var link in links){i++;}
    return i;
}

And i noticed it's won't return the correct number of a tags.

Any idea what can by the problem?

Any idea if there is any other way to get all the href in an Html ?

Edit

I tried this method on this html : http://mp3skull.com/mp3/nirvana.html . And i get this result:"1". but there are more results in the page.

like image 676
YosiFZ Avatar asked Feb 16 '14 13:02

YosiFZ


People also ask

How do I count elements in HTML?

To count all HTML elements, we use length property. The length property is used to count number of the elements of the jQuery object.

How will you count all the elements in a webpage?

To count the total number of web elements in the web page using Selenium for Java, find elements using XPath with expression to match any web element. driver. findElements(By. xpath("//*")) returns a list containing all the web elements present in the web page.

How do I count elements in a div?

To count all elements inside a div elements, we use find() method and length property. The find() method is used to find all the descendant elements of the selected element.

How can I count the number of elements with same class?

To count the number of elements with a specific class: Use the querySelectorAll() method to get a collection of the matching elements. Access the length property on the collection. The length property will return the number of matching elements.


1 Answers

You don't need a loop here. You can read length property.

function getACount() {
    return document.getElementsByTagName('a').length;
}
like image 197
dfsq Avatar answered Sep 30 '22 12:09

dfsq