views:

54

answers:

5

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?

+8  A: 

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)

Pekka
Just to make sure: Will accessing the properties through the element's style object *also* return the computed value?
Tomalak
@Tomalak no, `style` will give you the value explicitly specified in `style=` only.
Pekka
+1 Nice answer on css and style differences/access.
Mark Schultheiss
@Pekka: Thanks.
Tomalak
+1 Very nice @Pekka!
Marko
@Marko Thanks! ` `
Pekka
+1  A: 

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.

Tomalak
+4  A: 

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
Dustin Laine
A: 

using .css() will return an integer + px, but you can easily get a nice clea int by doing this: var yourVar = parseInt($('selector').css('top'));

Skatebail