Skip to content Skip to sidebar Skip to footer

Counting Div Elements Based On Id

I have a page similar to:

Solution 1:

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

Solution 2:

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

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)

Post a Comment for "Counting Div Elements Based On Id"