Jquery retrieves the css style specified directly on an element

How can I use jQuery to determine if an element has a specific style embedded in a string.

For example, given a document

<style> .MyClass { position: relative } </style> ... <div class="MyClass" id="div1" style="position: absolute"/> <div class="MyClass" id="div2"/> ... <script> function f() { assert($('#div1').SOMETHING('position') == 'absolute'); assert($('#div2').SOMETHING('position') == ''); } </script> 

If I use .css ('position'), div2 is reported as "relative". How to determine which styles were actually set in a string?

+4
source share
4 answers

I finished work

 assert($('#div2').get(0).style.position == 'relative'); 

but I was hoping for a more convenient way to do this.

+2
source

You can create your own custom selector:

 $(document).ready(function(){ $.extend($.expr[':'], { positionAbsolute: positionAbsolute, }); }); function positionAbsolute(el) { return $(el).css("position").indexOf("absolute") >= 0; } 

And then access it like this

 if ($("#MyDiv").is(":positionAbsolute")){ alert("Position absolute"); } 

Should the style be inline? If you declared it in a CSS class, for example,

 .positionAbsolute{position: absolute} 

and then you can use the selctor class instead:

 if ($("#MyDiv").is(".positionAbsolute")){ alert("Position absolute"); } 
+3
source

what about .attr('style') ?
And here is the link to jQuery docs.

+1
source

Well, you can just use the .css method, this returns all the styles attached to this element.

-1
source

All Articles