views:

327

answers:

3

Still trying to figure out idiomatic jQuery - here's some jQuery for setting a variable base on the class of a div - is there a jQuery way of doing this more compactly, given that the div in question may have more than one class ...

var currentType = 'component';
// text_component, image_component, tagged_component
if ($(my_div).hasClass('.text_component'))   { currentType = 'text_component' };
if ($(my_div).hasClass('.image_component'))  { currentType = 'image_component' };
if ($(my_div).hasClass('.tagged_component')) { currentType = 'tagged_component' };  

var dialog_box = $('div[id^='+currentType+'_dialog]');
A: 

When testing using hasClass, do not include the . (dot).

As for a simpler way, you could shorten it, but using hasClass is probably the best way.

I'm assuming the classes have priority (so the latter ones in the series of if take precedence over the others if there is more than one class)? Or do you want to support multiple "components"?

Here's a more efficient version that shows better what is happening:

var currentType, div = $(my_div);
// text_component, image_component, tagged_component
if (div.hasClass('tagged_component')) currentType = 'tagged_component';
else if (div.hasClass('image_component')) currentType = 'image_component';
else if (div.hasClass('text_component')) currentType = 'text_component';
else currentType = 'component';

var dialog_box = $('div[id^='+currentType+'_dialog]');
Blixt
Thanks for the heads up over the '.'.
Dycey
+2  A: 
currentType = $(my_div).attr("class");

That will assign whatever is in the class attribute, thus also handling more than one class

If later on you will want to maybe do individual checking, you can just split the classes into an array of separate class values...like such :

var classes = currentType.split(' '); //return an array of separate class values
Andreas Grech
Yes, but the aim is to be able to immediatly use the currentType to get hold of an appropriate (hidden) dialog div. In which case I would then have to add some sort of check for whether or not (say 'text_component') was in the array. Or am I missing something?
Dycey
+1  A: 

If i get you correct, I would suggest you to use metadata plugin which is written by John Resig (creator of jquery), you can set any data on any div element for later use. And you won't need to fetch arguments from css class. You can read that data whenever you want.

sample markup: (from plugin page)

<div class="someclass {some: 'data'} anotherclass">...</div>

then in javascript:

var data = $('div.someclass').metadata();
if ( data.some == 'data' ) alert('It Worked!');

hope it helps, Sinan.

Sinan Y.
Spot on! That's exactly the sort of thing I was looking for... means I don't have to keep adding tests for new component classes. Thanks.
Dycey
You're welcome, this saved me also a good amount of time in past :)
Sinan Y.