user7402861
user7402861

Reputation:

Converting string to javascript words

I am using this to find all elements inside some div:

var counts = {}
var element = 'div';
$('.workspace').find('*').each(function() {
    var tag = this.tagName.toLowerCase();
    counts[tag] = counts[tag] || 0;
    counts[tag] ++;
});

Now I am checking does element exist in counts:

if(el in counts)

And if it does I am need to get number of divs with: counts.div but since div is string in var element I need to use counts.element and there I get error undefined because it can't find element its like I said counts.'elements'.

Basically when i use counts.div or counts.header etc I get number of how many divs are there inside some element. How can I accomplish this?

Upvotes: 0

Views: 38

Answers (2)

guest271314
guest271314

Reputation: 1

You are already using jQuery, use jQuery() , .filter()

var counts = $(".workspace *");
var element = "div";
var len = counts.filter(element).length;

Upvotes: 1

le_m
le_m

Reputation: 20228

Are you looking for counts[element]? This is called bracket notation. You already used it when accessing counts[tag]++.

Upvotes: 2

Related Questions