Reputation: 10256
I have div with 6 classes. I want to know if that div has either class one, two , three, or four and set that as the value of the select box. I only want to search for these 4 classes and don't care about the other classes in the div. I have the following. Is there a better way to write it.
<div class="four whatever something"></div>
<select>
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
</select>
if ($('div').hasClass(one)) {
$('select').val('one')
} else if ($('div').hasClass('two')) {
$('select').val('two')
}
if ($('div').hasClass('three')) {
$('select').val('three')
}
if ($('div').hasClass('four')) {
$('select').val('four')
}
Upvotes: 1
Views: 125
Reputation: 3091
You could try something like that:
var classes = $('div').attr('class').split(/\s/);
for ( var i in classes )
$('select').val(classes[i]);
Upvotes: 1
Reputation: 359816
Of course there is a better way to write it. You'd probably like to know what that way is, though. :)
var classes = ['one', 'two', 'three', 'four'],
$div = $('#myDivId');
for (var i=0; i<classes.length; i++)
{
if ($div.hasClass(classes[i]))
{
$('select').val(classes[i]);
// break;
}
}
The break;
is commented out to make the looped version match your current code. However, if you meant to use if...else if...else if...else if
instead of if...if...if...if
, the break
is necessary.
Upvotes: 1