3

Is there a way using pure javascript to check if a CSS class is defined, and if it is, then use it, and if not, define a custom style?

Example:

If CSS class demo_class does not exist:

<div style="text-size:12px">Some content here...</div>

Else:

<div class="demo_class">Some content here...</div>
hopper
  • 13,060
  • 7
  • 49
  • 53
DomingoSL
  • 14,920
  • 24
  • 99
  • 173
  • 1
    possible duplicate of [How can you determine if a css class exists with Javascript?](http://stackoverflow.com/questions/983586/how-can-you-determine-if-a-css-class-exists-with-javascript) – Nerius Aug 06 '13 at 08:18

2 Answers2

-1

Forst you need to select that element, for example give it some id

<div id="some-id">Some content here...</div>

js:

var element=document.getElementById('some-id');

Now you can check its class and set style

if(element.class!='demo_class')
{
  element.style.fontSize='12px';
}
Hubu
  • 59
  • 2
  • 2
    I think he wants to check if the classname is defined in the css (not if the element has the class) – xec Aug 06 '13 at 08:26
-1

You can do this:

if(typeof $('#some-id').attr('class') != 'undefined'){
    if($('#some-id').attr('class').indexOf('demo_class') > -1) {
        //Exist the class in the div
    } else {
        //Not exist the class in the div
        $('#some-id').addClass('demo_class');
    }
} else {
    $('#some-id').addClass('demo_class');
}