0

So I am using the following jQuery to get a count of all items in HTML with a class containing box. However it is not returning correctly, I feel like I'm missing something stupid.

var counter = $("*[class^=box]").length;

JSFiddle for example: jsfiddle This link should return 1, but it returns 0.


EDIT:

It was a stupid mistake:I was previously using ID which was only going to be box1,box2,box3,etc so it made sense then. I knew it was stupid.

var counter = $("*[class=box]").length;
Ucf_Falcon
  • 39
  • 8
  • 1
    Why do you need this? It sounds like an A/B problem. It's also not a straightforward one to solve, as you need to grab all elements, then split the classes of each element into an array and filter that array by items containing the required string. I'm sure there is a better way of achieving whatever you need. – Rory McCrossan May 13 '14 at 14:08
  • check this out `http://stackoverflow.com/a/2220874/1826335` – Catalin Deaconescu May 13 '14 at 14:10
  • I'm dynamically adding styles based on the count. So I add box0 for first box 1 for second, etc. If the count is wrong the argument I have more than one element with the same class which I'm trying to keep unique so I can retrieve the inner HTML later if certain actions are taken. – Ucf_Falcon May 13 '14 at 14:11
  • The 0 is actually 1 element having the class, if you add another element you'll get 1 etc. It's 0 based counting – alou May 13 '14 at 14:14
  • @alou - 0 based counting, really ? – adeneo May 13 '14 at 14:17
  • lol that sounded stupid indeed – alou May 13 '14 at 14:18

2 Answers2

3

The "attribute starts with selector" matches the attribute, not neccesarely the classname

That means that this will match the selector

<div class="box0 emailbodytext" ...

as the attribute starts with "box", while this won't

<div class="emailbodytext box0" ...

as the attribute does not start with "box", even if one of the classes do


Here's one way to solve it

var counter = $('*').filter(function() {
    return this.className.split(/\s+/).filter(function(klass){
        return klass.indexOf('box') === 0;
    }).length;
}).length;

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
2

Your selector basically checks for elements that their class attribute starts with 'box'. Your have more than one class name in your class attribute so you need to use 'contains' instead of 'starts with'. Example:

var counter = $("*[class*=box]").length;
Avi L
  • 1,558
  • 2
  • 15
  • 33