Jason Sweeters
Jason Sweeters

Reputation: 161

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.

Upvotes: 1

Views: 110

Answers (4)

Louis Jordan
Louis Jordan

Reputation: 11

In my opinion, the other answers are a little overkill. You can use attribute selectors to specify an exact attribute value like so:

$('span[class="a b"]')

So long as you're sure the element you want to select will only have those classes this will work.

Upvotes: 0

atmd
atmd

Reputation: 7490

you can use the jquery not() method to take elements out of the results (the oppersite of add()). here are the docs.

var results = $('.a').add('.b').not('.c');

if you only want elements with the class of .a AND .b and no other classes, you'd need to do a reg ex on the el.className. checking for any other class name segments in addition to .a and .b, something like this:

$(function () {
    var results = $('.a.b');

    var onlyAAndB = results.filter(function (index, el) {
        var classes = el.className;
        var remaining = classes.replace('a', '').replace('b', '').replace(' ', '');
        if(!remaining) {
            return el;
        }
    });

    console.log(onlyAAndB);
});

The above is the longway round and can be shorted with regex rather then replace, im using replace here just to demonstrate the process

Upvotes: 1

Subhan
Subhan

Reputation: 1634

Something like: $(":not(selector)")

Example: Select all <p> elements except those with class="intro":

$("p:not(.intro)")

In the case you don't want to use not method, try this: $(selector).filter(criteria,function(index))

Example: Return all <p> elements with class name "intro":

$("p").filter(".intro")

Upvotes: 1

Paul Roub
Paul Roub

Reputation: 36458

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>

Upvotes: 1

Related Questions