tags:

views:

638

answers:

4

How can I use jQuery to determine whether an element has a certain style set inline.

E.g, given the 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 being 'relative'. How can I determine which styles have actually been set inline?

+1  A: 

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

Traveling Tech Guy
just remember that if you use `attr('style')` you get "position:relative" in return and every other inline style as well...
peirix
I could do that, but then I'd have to parse the returned string. I'm going to set more styles than the position inline.
erikkallen
+3  A: 

You could 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 this like so

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

Does the style have to be inline? If you declared it in a CSS class, e.g,

.positionAbsolute{position: absolute}

and then you could use a class selctor instead:

if ($("#MyDiv").is(".positionAbsolute")){
    alert("Position absolute");
}
James Wiseman
+1. Not because it solved my problem, but because it's a really cool thing to do. However, For the reason stated in the question I can not use .css('position')
erikkallen
Just got a down vote, and no explanation. That really irritates me (not the down vote, but the lack of explanation).
James Wiseman
A: 

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

James Brooks
I stated in the question why I could not do that.
erikkallen
+1  A: 

I ended up doing

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

but I was hoping for a more jQueryish way of doing it.

erikkallen
You could put this code into the custom selector as desribed in my answer below
James Wiseman
I could, but it wouldn't help me. My problem is "given this element, is its position set to relative?", but making the custom selector would solve the problem "Given these objects, which of them have their position set to relative?". That could also be a problem which someone need to solve, but not me, at least not now.
erikkallen