obmon
obmon

Reputation: 337

Jquery Selecting a class when multiple class are present

I have the following in a jquery script:

if ( path[1] ) {
    $('.content_nav a[class$="' + pos1_path + '"]').toggleClass('current');
}

which selects the appropriate element, such as:

<a class='pos1_path' href="#">link</a>

It works, but now I need the same to work when multiple classes are used, like this:

<a class='pos1_path pos2path' href="#">link</a>

How can I achieve this?

SOLVED:

$('.content_nav a[class$="' + pos1_path + ' ' + pos2_path + '"]').toggleClass('current');

Upvotes: 1

Views: 732

Answers (4)

ieeehh
ieeehh

Reputation: 674

You could just concat the classes and maybe use a context

var $context = $('.content_nav');
$('.pos1_path.pos2path', $context);

Or, alternatively, if you want to select one class OR another:

var $context = $('.content_nav');
$('.pos1_path, .pos2path', $context);

Upvotes: 1

alanmanderson
alanmanderson

Reputation: 8230

You can try this which will take your string replace the spaces for commas. That will select all elements that have any of the classes. IF that is what you want.:

var classList = path[1].replace(" ",",.");
if $('.content_nav a[class$=".' + classList + '"]').toggleClass('current');

Upvotes: 0

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this:

if ( path[1] ) {
    if($('.content_nav a').hasClass(pos1_path))
          $('.content_nav a').toggleClass('current');
}

For multiple selectors you can refer http://api.jquery.com/category/selectors/

Upvotes: 0

Vlad Magdalin
Vlad Magdalin

Reputation: 1690

You can use multiple selectors with jQuery:

$('.content_nav a.pos1_path, .content_nav a.pos2_path').toggleClass('current');

If you want both classes to exist in order to select the element, then you can do something like this:

$('.content_nav a.pos1_path.pos2_path').toggleClass('current');

I've left out the string concatenation for clarity.

Upvotes: 3

Related Questions