Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get attribute out of style

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?

like image 415
skerit Avatar asked Aug 23 '10 21:08

skerit


People also ask

How can check CSS property value in jQuery?

Get a CSS Property Value You can get the computed value of an element's CSS property by simply passing the property name as a parameter to the css() method. Here's the basic syntax: $(selector). css("propertyName");

What is the use of CSS () method in jQuery?

jQuery css() Method The css() method sets or returns one or more style properties for the selected elements. When used to return properties: This method returns the specified CSS property value of the FIRST matched element.

What is .attr in jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

How get data attribute value in jQuery?

To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).


4 Answers

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)

like image 124
Pekka Avatar answered Oct 02 '22 08:10

Pekka


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
like image 33
Dustin Laine Avatar answered Oct 02 '22 07:10

Dustin Laine


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);
like image 21
michaeltintiuc Avatar answered Oct 02 '22 07:10

michaeltintiuc


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.

like image 24
Tomalak Avatar answered Oct 02 '22 06:10

Tomalak