xerwudjohn
xerwudjohn

Reputation: 63

how to check the div value in javascript

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

Answers (4)

gregorkas
gregorkas

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

Arun P Johny
Arun P Johny

Reputation: 388316

it can be shorten as

var t = 'divalue';
$('.divname.' + t).css('background', '#0962ae');

Upvotes: 2

Kuzgun
Kuzgun

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

xdazz
xdazz

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

Related Questions