0

The title might have been confusing, anyways, basically let's say this is how my HTML looks like:

<span></span>
<span></span>
<div class='box'>
<span></span>
<span></span>
<span class='doNotCountThisOne'>
</div>
<span></span>
<span></span>

So this would return 2. Basically I want to check for all <span>s within a specific class (box in this case) that does not contain their own classes. (I.E like the doNotCountThisOne span)

I tried something like:

var cAmounts = 0;
var test = $(".box span:not([class]), span[class='']");
test.each(function() {
   cAmounts++;
   console.log(cAmounts);
}

But it seems to add all <span>s without a class on the whole page. Thanks in advance.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
prk
  • 3,781
  • 6
  • 17
  • 27
  • 2
    That is because the second rule `, span[class='']` matches all the spans without a class in the whole page. Remove it. – XCS Jul 24 '14 at 09:49
  • 2
    Are you sure it counts all of these elements? Even without the contextual selector, `span[class='']` could not possibly match any of them since none of them have an empty `class` attribute - they either have a non-empty `class` attribute, or *no* attribute at all. – BoltClock Jul 24 '14 at 09:52
  • See also: [Select elements without any class](http://stackoverflow.com/questions/4991576/select-elements-without-any-class) – BoltClock Jul 24 '14 at 10:00

2 Answers2

2

Try,

var test = $(".box span:not([class]), .box span[class='']");

Your code wont give expected result because, the second selector in the multiple selector does not have any context. so that it would search around the entire DOM.

Your code can be shortened as,

var cAmounts = $(".box span:not([class]").length;
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
1

In $(".box span:not([class]), span[class='']");, why do you add span[class=''] ? It will add to the result all span with an empty class. Remove this and you'll get what you want :)

$(".box span:not([class])");

P.Grd
  • 43
  • 1
  • 7