Jason Sweeters Jason Sweeters - 7 days ago 6
jQuery Question

How to make jQuery select exactly the classes specified?

html

<span class="a">a</span>
<span class="a b">a b</span>
<span class="a b c">a b c</span>


javascript

var obj = $(".a.b"); //selects 2 spans .a .b and .a .b .c
alert($(obj).text());


How to make jQuery select the single span with the classes .a and .b only?

I can't use the jQuery not in my case because I might not know about class c ahead of time.

Answer

If you don't know the other class(es) ahead of time, you can filter out elements that have more than your two target classes:

var obj = $(".a.b").
  filter(
    function() {
      return( this.className.split(/\s+/).length == 2 );
    }
  );

console.log($(obj).text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="a">a</span>
<span class="a b">a b</span>
<span class="a b c">a b c</span>