erikkallen
erikkallen

Reputation: 34391

jquery retrieve css style set directly on element

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?

Upvotes: 4

Views: 1792

Answers (4)

erikkallen
erikkallen

Reputation: 34391

I ended up doing

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

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

Upvotes: 2

Mutation Person
Mutation Person

Reputation: 30498

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

Upvotes: 3

James Brooks
James Brooks

Reputation: 1311

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

Upvotes: -1

Traveling Tech Guy
Traveling Tech Guy

Reputation: 27811

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

Upvotes: 1

Related Questions