0

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?

6
  • 1
    Are you looking for counts[element]? <-- bracket notation Commented May 21, 2017 at 21:46
  • @le_m take the 15 seconds to write the answer and you'll get my upvote Commented May 21, 2017 at 21:46
  • Oh my god I am brain dead! Make an answer I will upvote. Commented May 21, 2017 at 21:47
  • @JoeFrambach Ok ok, I posted it as an answer ;) Commented May 21, 2017 at 21:48
  • @NoNameIamLame Don't worry, we will revive you ;) Commented May 21, 2017 at 21:49

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

1 Comment

Alternatively $(element).is(counts)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.