根据id计算div元素 [英] Counting div elements based on id
问题描述
我有类似的网页:
< div id =content>
< div id =boxes>
< div id =box:content:1:text/>
< div id =box:content:2:text/>
< div id =another_id/>
< div id =box:content:5:text/>
< / div>
< / div>
我想知道id与表达式框匹配的div的数量:content:X:text (其中X是一个数字)。我可以使用纯javascript或jquery来做到这一点。
但是在内部框中,我可以有几种类型的div,我不想数(another_id)和我可以从一个元素的X和下一个元素之间存在差距,它们不是按顺序排列的。
我正在寻找一种获取基于正则表达式的元素的方法,但是我还没有找到任何有趣的方式。这是一种可能的方法吗?
谢谢
jQuery:
$(div [id])。filter(function(){
return!(/ ^ box:内容:\ d +:text $ /。test(this.id));
})。size();
纯粹的JavaScript:
var elems = document.getElementsByTagName(div),
count = 0;
for(var i = 0,n = elems.length; i< n; ++ i){
if(typeof elems [i] .id ==string&& / ^ box:content:\d +:text $ /。test(this.id)){
++ count;
}
}
I have a page similar to:
<div id="content">
<div id="boxes">
<div id="box:content:1:text" />
<div id="box:content:2:text" />
<div id="another_id" />
<div id="box:content:5:text" />
</div>
</div>
I want to know the number of div with id that matches the expression box:content:X:text (where X is a number). I can use pure javascript or jquery for doing that.
But inside boxes i can have several types of divs that i don't want to count ("another_id") and i can have gaps from the X of an element and the next element, they are not in sequence.
I was searching a way to gets the elements based on a regexp but i haven't found any interesting way. Is it a possibile approach ?
Thanks
jQuery:
$("div[id]").filter(function() {
return !(/^box:content:\d+:text$/.test(this.id));
}).size();
Pure JavaScript:
var elems = document.getElementsByTagName("div"),
count = 0;
for (var i=0, n=elems.length; i<n; ++i) {
if (typeof elems[i].id == "string" && /^box:content:\d+:text$/.test(this.id)) {
++count;
}
}
这篇关于根据id计算div元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!