Jquery: How to check if the element has certain css class/style

JavascriptJqueryCss

Javascript Problem Overview


I have a div:

<div class="test" id="someElement" style="position: absolute"></div>

Is there any way to check if the certain element:

$("#someElement") 

has a particular class (in my case, "test").

Alternately, is there a way to check that en element has a certain style? In this example, I'd like to know if the element has "position: absolute".

Thank you very much!

Javascript Solutions


Solution 1 - Javascript

CSS Styles are key-value pairs, not just "tags". By default, each element has a full set of CSS styles assigned to it, most of them is implicitly using the browser defaults and some of them is explicitly redefined in CSS stylesheets.

To get the value assigned to a particular CSS entry of an element and compare it:

if ($('#yourElement').css('position') == 'absolute')
{
   // true
}

If you didn't redefine the style, you will get the browser default for that particular element.

Solution 2 - Javascript

if($('#someElement').hasClass('test')) {
  ... do something ...
}
else {
  ... do something else ...
}

Solution 3 - Javascript

if ($("element class or id name").css("property") == "value") {
    your code....
}

Solution 4 - Javascript

Or, if you need to access the element that has that property and it does not use an id, you could go this route:

$("img").each(function () {
        if ($(this).css("float") == "left") { $(this).addClass("left"); }
        if ($(this).css("float") == "right") { $(this).addClass("right"); }
    })

Solution 5 - Javascript

i've found one solution:

$("#someElement")[0].className.match("test")

but somehow i believe that there's a better way!

Solution 6 - Javascript

Question is asking for two different things:

  1. An element has certain class
  2. An element has certain style.

Second question has been already answered. For the first one, I would do it this way:

if($("#someElement").is(".test")){
    // Has class test assigned, eventually combined with other classes
}
else{
    // Does not have it
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question0100110010101View Question on Stackoverflow
Solution 1 - JavascriptTamas CzinegeView Answer on Stackoverflow
Solution 2 - JavascriptDarin DimitrovView Answer on Stackoverflow
Solution 3 - JavascriptSandeep GuptaView Answer on Stackoverflow
Solution 4 - JavascriptkelseedevView Answer on Stackoverflow
Solution 5 - Javascript0100110010101View Answer on Stackoverflow
Solution 6 - JavascriptMario VázquezView Answer on Stackoverflow