Pon Somean
Pon Somean

Reputation: 143

How to get style.left

Does anyone know, I have a div element when the first load I set its attributes to right:0 and bottom:0; I want to get its style.left but it return NaN. So how to get it or is there another way?

<div id="myDiv">Sample</div>
<script type="text/javascript">
    var setMe = document.getElementById("myDiv");
    setMe.setAttribute("style", "background-color: red;
        position: absolute;
        width: 670px;
        height: 370px;
        right: 0;
        bottom: 0;");
    alert(setMe.style.left)
</script>

Upvotes: 0

Views: 1172

Answers (3)

nicosantangelo
nicosantangelo

Reputation: 13726

you have three options:

style property // --> Returns an object that represents the element's style attribute (setted when parsed)

getAttribute // --> returns the value of the named attribute on the specified element.

computedStyle // -->  gives the final used values of all the CSS properties of an element.

Take a look at this fiddle (demo) for an example in every one.

Also:

Upvotes: 0

loxxy
loxxy

Reputation: 13151

Try it using getComputedStyle(): (Demo)

var setMe=document.getElementById("myDiv");

setMe.setAttribute("style", "background-color:red;position:absolute;width:670px;height:370px;right:0;bottom:0;");

alert(window.getComputedStyle(setMe).left);

Upvotes: 1

Iswanto San
Iswanto San

Reputation: 18569

Use offsetLeft attribute.

<html>
<head></head>
<body>
<div id="myDiv">Sample</div>
<script type="text/javascript">
    var setMe=document.getElementById("myDiv");
    setMe.setAttribute("style", "background-color:red;position:absolute;width:670px;height:370px;right:0;bottom:0;");
    alert(setMe.offsetLeft);
</script>
</body>
</html>

Upvotes: 0

Related Questions