Converting string to javascript words

时间:2017-05-21 21:37:45

标签: javascript

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?

2 个答案:

答案 0 :(得分:2)

您在寻找counts[element]吗?这称为bracket notation。您在访问counts[tag]++时已经使用过它。

答案 1 :(得分:1)

您已使用jQuery,请使用collect(...)jQuery()

.filter()