Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element tag name and length with Jquery each

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.

like image 224
Youss Avatar asked Dec 20 '22 20:12

Youss


2 Answers

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 
like image 43
meagar Avatar answered Jan 07 '23 06:01

meagar


Try it:

var count =  $(string, 'body').length;
like image 184
FBHY Avatar answered Jan 07 '23 07:01

FBHY