jQuery get attribute out of style

45,055

Solution 1

It depends what you need. If you need the computed value - e.g. the actual value the browser used after parsing all the style sheets - use

$("#element_1").css("top")
$("#element_1").css("left")

If it's a pixel value, that is always going to be the one specified in the style property - unless that was overridden by an !important statement in a style sheet.

jQuery docs for .css()

If you explicitly need the value specified in the element's style property, use

$("#element_1")[0].style.top
$("#element_1")[0].style.left

unlike .css(), these values will be empty if they were not specified in the style property.

(Using ID element_1, you can't have an ID named 1)

Solution 2

You can use the CSS function:

var topValue = $(this).css("top"); //Change the selector to meet your needs
var leftValue = $(this).css("left"); //Change the selector to meet your needs

Solution 3

using .css() will return an integer + px, but you can easily get a nice clean integer by doing this:

var yourVar = parseInt($('selector').css('top'), 10);

Solution 4

CSS properties are accessible through standard DOM properties:

alert( $("#theElement")[0].style.top ) // "250px"
alert( $("#theElement")[0].style.left ) // "250px"

As an aside, "1" is not a valid HTML element ID.

Share:
45,055

Related videos on Youtube

Jelle De Loecker
Author by

Jelle De Loecker

Updated on June 18, 2020

Comments

  • Jelle De Loecker
    Jelle De Loecker about 4 years

    I need to extract something out of the "style" attribute: the "top" and "left" attribute

    <div style="top: 250px; left: 250px;" id="1" class="window ui-draggable">
    

    What's the best way of doing this with jQuery? Is there an easy way, or will I have to resort to string functions?

  • Tomalak
    Tomalak almost 14 years
    Just to make sure: Will accessing the properties through the element's style object also return the computed value?
  • Pekka
    Pekka almost 14 years
    @Tomalak no, style will give you the value explicitly specified in style= only.

Related