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>
1

2 Answers 2

-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';
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think he wants to check if the classname is defined in the css (not if the element has the class)
-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');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.