views:

57

answers:

5

Hi,

I have the following jQuery code which all works fine:

         $("#sidebar .m3, #sidebar .m5").toggle(function() {                  
               $(this).find("img").attr({­src:"images/Up.png"});                 
               }, function() {
               $(this).find("img").attr({­src:"images/Down.png"});                  
         }); 

My question is, instead of individually specifying $("#sidebar .m3, #sidebar .m5"), where my menu items may have the classes m1,m2,m3,m4,m5 etc, is there anyway of having something like:

$("#sidebar .m[*]").

That will cater for any number after the ".m" , so I don't need to hard code m3 or m5?

Thanks.

+5  A: 

If that's the only (or first) class applied to the menu item you can use the attribute starts with selector.

$('#sidebar [class^=m]')...

A better way would be to give them all a common class, like menu-item, in addition to your other class that functions simply as a selector to group them all, then simply use:

$('#sidebar .menu-item')...
tvanfosson
+1 tho just to clarify the menu item would end up looking something like `<li class="m1 menu-item">...</li>`
Darko Z
@Nick -- that's the first sentence in the answer.
tvanfosson
@tvanfosson - Hahaha, had my screen scrolled where that line was just out of view, removing that ignorant comment :)
Nick Craver
@tvanfosson - thanks for that and thanks to all.
tonsils
A: 

take a look here

griegs
+2  A: 

Can you tackle it a slightly different way???

If you have the ability to manipulate your HTML could add an additional class to all the menu items as a placeholder (for example, call the class 'm').

This would allow you to search on: $("#sidebar .m)

Boycs
missed a space between the two selectors..
Gaby
Thanks Gaby, selector fixed
Boycs
A: 

You could use the begins-with selector:

$("#sidebar *[class^='m']")
You
+3  A: 

You can also do this:

$(".m3, .m5", "#sidebar")

But...you're not restricted to one class, can you just use multiple? To use multiple classes just have a space between them, for example:

<div class="m5 myClass">Stuff</div>
<div class="m3 myClass">Stuff 2</div>

Then you can use that class, like this:

$("#sidebar .myClass")

Or, say your structure is like this:

<div id="sidebar">
  <div class="m5">Stuff</div>
  <div class="m3">Stuff 2</div>
</div>

You can just use the child-selector, like this:

$("#sidebar > div")

There are of course other ways to skin this cat as well, it just depends on what your markup is.

Nick Craver