Reputation: 63
How to set the div CSS styles using javascript? I have a problem with getting the value of class name. Please help if anyone know it.
<div class="this_is_i_want_to_set_the_background_color" id="divname"></div>
<div class="test" id="divname"></div>
var className = $('.divname').attr('class');
var t = 'divalue';
if(className == t){
$('.divname').css('background', '#0962ae');
}
Upvotes: 2
Views: 93
Reputation: 137
You can try the jQuery hasClass function (doc: http://api.jquery.com/hasClass/), for example:
if($('.divname').hasClass('divalue')){
$('.divname').css('background', '#0962ae');
}
Upvotes: 0
Reputation: 388316
it can be shorten as
var t = 'divalue';
$('.divname.' + t).css('background', '#0962ae');
Upvotes: 2
Reputation: 4737
In your example, you already select only '.divname' ? It will never work because it becomes like this:
if('divname'=='divvalue')
Instead, you can write what you want to achieve and we can help.
Upvotes: 0
Reputation: 160833
You may use .hasClass
method:
$('.divname').each(function() {
if ($(this).hasClass('divalue')) {
$(this).css('background', '#0962ae');
}
});
But there is one simpler way to do this:
// an element with class 'divname' also has class 'divalue'
$('.divname.divalue').css('background', '#0962ae');
Upvotes: 5