20

Possible Duplicate:
How can you determine if a css class exists with Javascript?

Is there a way to check if there is a class named 'some-class-name' in css?

For example, I have:

<style type="text/css">
    .box {
        position: absolute;
        left: 150%;
    }
</style>

My intention is to randomly assign a class to a div on certain event:

var classList = []; //Need to populate this array
$('#updateClass').on('click', function() {
    $('#resultDiv').attr('class',classList[Math.floor((Math.random()*classList.length)+1)]);
}); 

Is it possible to check by JS/jQuery whether a class named 'box' exists in the stylesheet?

I referred to This Question - How can you determine if a css class exists with Javascript?, But the answer didn't help me because the link in the answer doesn't exists anymore.

Thanks.

11
  • 10
    check this answers: stackoverflow.com/questions/983586/… Commented Dec 19, 2012 at 7:45
  • 2
    if ($('.validation-errors').length){ /*your code here */ } but i suspect it will check element has class ?? Commented Dec 19, 2012 at 7:46
  • Is there any reason for you to check for class names in css? Commented Dec 19, 2012 at 7:46
  • 6
    other question, why you want to do this? whats the reason? Commented Dec 19, 2012 at 7:48
  • @silly I read that as whats the "season", the winter bash is getting to me Commented Dec 19, 2012 at 7:53

2 Answers 2

1

As mentioned above (How can you determine if a css class exists with Javascript?), you could scan the complete CSS for the requested class, or you could add the requested class to an element and check if the attriubtes of the class apply to it. For example:

document.getElementById('yourTestElementID').className=newClass;
if(document.getElementById('yourTestElementID').style.position === 'thevalue' ) {
  // class exists....
}
Sign up to request clarification or add additional context in comments.

Comments

-2

Your random algorithm:

Math.floor((Math.random()*classList.length)+1)

will generate random number from specific range or more generally from 1 to classList.length.

You just need to be sure that the class names that you are going to use and will be populated in the array will exists.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.