最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Counting div elements based on id - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question asked Nov 7, 2009 at 14:01 semantic-devsemantic-dev 1,1333 gold badges14 silver badges29 bronze badges 1
  • 3 Why not giving them class names? That would be a much cleaner way. – Boldewyn Commented Nov 7, 2009 at 14:05
Add a ment  | 

2 Answers 2

Reset to default 4

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;
    }
}

To expand on Boldewyn's ment, you can provide multiple classes delimited by spaces, and then work with those classes separately or in bination.

This probably removes the need for the ids, but I've left them in just in case:

<div id="content">
<div id="boxes">
  <div id="box:content:1:text" class="box content 1 text" />
  <div id="box:content:2:text" class="box content 2 text" />
  <div id="another_id" />
  <div id="box:content:5:text" class="box content 5 text" />
</div>
</div>


And then with jQuery you can count just the desired items with:

$j('#content>#boxes>.box.content.text').length

(or perhaps just use '#boxes>.box.text' or whatever works for what you're trying to match)

发布评论

评论列表(0)

  1. 暂无评论