0

How to get the css property from external source using js/jquery if the inline style is applied to the same element? Example:

<div id="my" style='left:100px'>some content</div>
<style>
    #my{left:250px;}
</style>

I want to return 250px, if that's possible without removing the inline style?

2
  • You are specifically getting the stylings applied to an ID, correct? Because there's an easier way if you're talking about an element that does not have to be unique. Commented Aug 17, 2012 at 17:41
  • #my{left:250px!important;} will override inline style. Commented Aug 17, 2012 at 18:07

3 Answers 3

3

Are you able to alter the markup after the page loads? If so, I would use jQuery to change the style attribute to an empty value. Then I would get the left value via jQuery.

var my = $('#my');
my.attr('style','');
var position = my.position();
alert(position.left);

or if you don't want to cache the var:

$('#my').attr('style','');
alert($('#my').position().left);
Sign up to request clarification or add additional context in comments.

6 Comments

This will work. I was already working on a Fiddle for this (jsfiddle.net/gromer/pRetH).
This works, but it might cause a slight "blink" between positions if you're going to restore the contents of style afterwards.
Actually i am adding that inline-style after the page load, so i can get the css value before that function and store it in the global var. But i was just wondering if that's possible to achieve without that extra var? Your code is good , but i would stick to my current code...
You could do it without the var. Just good practice in terms of speed to cache the object. That way, jQuery only has to search for the element once.
Bravo Moettinger, that's it! If you want, write that as an answer so i can confirm it...
|
1

I think the best option is to just remove the inline style for a moment, reading it out and putting it back.

You won't see any graphical changes to the element while the style is taken away. It just goes too fast.

http://jsfiddle.net/fp7UB/

function readstyle() {
    var el = document.getElementById('my');
    var attr = el.getAttribute('style');
    el.setAttribute('style', '');
    var val = el.offsetLeft;
    el.setAttribute('style', attr);
    return val;
}​

Comments

0

One way to do this is to download the .css file via AJAX (you can use the easy-to-use jQuery $.get()), and then parse it using JSCSPP or something equivalent (another parser which is written in jQuery). While this might be considered an overkill, it gives you the advantage that you can access all the rules after one grabbing process.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.