Ankit Kumar Pandey
Ankit Kumar Pandey

Reputation: 27

object.style.left returns nothing in javascript?

I am unable to access the left position of an image element. Here is the my jsFiddle. The alert box is displaying nothing.

<!DOCTYPE html>
<html>
<img src="pan.jpg" id="uno" width="600" />
<style>
#uno
{
position:relative;
left:100px;
}
</style>
<script>
     alert(document.getElementById("uno").style.left);
</script>
</html>

Upvotes: 0

Views: 1239

Answers (2)

Mudassir Ali
Mudassir Ali

Reputation: 8041

Alternate Solution(if you do not define inline styles, little complicated though)

//document.styleSheets gives the list of available stylesheets for the document
//Here we have only one stylesheet hence document.stylesheets["0"] gives us the only stylesheet    
//document.stylesheets["0"].rules gives the object with defined css rules
var rules = document.styleSheets["0"].rules
//iterating over that object to find the object which has css for element ID "uno"
for(property in rules){
  if(rules.hasOwnProperty(property)){
    if(rules[property].selectorText === "#uno"){
      alert(rules[property].style.left);
    }
  }
}

Updated File

<!DOCTYPE html>
<html>
<img src="pan.jpg" id="uno" width="600" />
<style>
#uno
{
position:relative;
left:100px;
}
</style>
<script>
  var rules = document.styleSheets["0"].rules
  for(property in rules){
    if(rules.hasOwnProperty(property)){
      if(rules[property].selectorText === "#uno"){
        alert(rules[property].style.left);
      }
    }
  }
</script>
</html>

rather use jquery which does all the hardlifting for us

Upvotes: 0

Daniel Imms
Daniel Imms

Reputation: 50229

JavaScript's style property only has access to inline styles. You'll notice it works with this: (jsFiddle)

<img src="pan.jpg" id="uno" width="600" style="left:125px;" />

I suggest you either only set left in JavaScript or use classes in CSS and check the object for the class instead of the style.

Upvotes: 3

Related Questions