views:

144

answers:

2

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

+4  A: 

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;
    }
}
Gumbo
the lesser "i dont know regex approach": alert($("#boxes div[id^=box:content:][id$=text]").length); :)
Les
+1 - So much for my answer.
James Black
+1  A: 

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)

Peter Boughton