Jquery: 如何检查元素是否具有某种 css 类/样式

我有一个 div:

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

有没有办法检查某个元素是否:

$("#someElement")

有一个特定的类(在我的例子中是“ test”)。

或者,是否有一种方法来检查 en 元素是否具有某种样式?在这个例子中,我想知道元素是否有“ position: absolute”。

非常感谢!

225265 次浏览
if($('#someElement').hasClass('test')) {
... do something ...
}
else {
... do something else ...
}

i've found one solution:

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

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

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.

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

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"); }
})

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
}