1

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');
obmon
  • 347
  • 2
  • 12
  • But why go through all that trouble when jQuery can make things simpler? – ieeehh Feb 12 '13 at 04:52
  • 1
    Like my answer below.. the first case. But ok, if you like the style you used better, then it's ok. It's just a matter of style I guess – ieeehh Feb 12 '13 at 04:56

4 Answers4

3

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.

Vlad Magdalin
  • 1,692
  • 14
  • 17
  • This led me to the answer. I have updated my original post to show the answer. Thank you. – obmon Feb 12 '13 at 04:50
1

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);
ieeehh
  • 674
  • 5
  • 10
0

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/

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

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');
ajon
  • 7,868
  • 11
  • 48
  • 86