I'm trying to get info about all element tags and there frequency in the page, this is how I find the tag, very simple:
$('body *').each(function(){
var string = this.tagName;
But the length doesnt catch up:
var count = $(this).length;
It gives me 1
while there are two divs, example: JsFiddle
I can solve this problem by removing the each
function but I need it for the tagname. I have to use body * for my project so I can't refer directly to the divs.
You're not iterating each kind of tag with body *
, you're iterating over each tag individually. The length will always be one, because this
is always a single DOM element.
You should enumerate the tags you want to count, and iterate over them:
var tags = ['div', 'li', 'a'];
tags.forEach(function (tag) {
console.log(tag, "appears", $('body ' + tag).length, 'times');
});
Output from running in the JS console on this page:
div appears 141 times
li appears 66 times
a appears 179 times
Try it:
var count = $(string, 'body').length;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With