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?
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");
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.
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.
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" ).
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
)
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
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With