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!
To check if an element's style contains a specific CSS property, use the style object on the element to access the property and check if it's value is set, e.g. if (element. style. backgroundColor) {} . If the element's style does not contain the property, an empty string is returned.
jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".
Get a CSS Property Value You can get the computed value of an element's CSS property by simply passing the property name as a parameter to the css() method. Here's the basic syntax: $(selector). css("propertyName");
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With