How to get a CSS attribute from a tag?

Asked

Viewed 838 times

5

Hello, I need a help. I would like to know how to get values from an html tag using javascript.

such as: take the marginLeft value of an image that was determined by a css file.

I hope I’ve been clear, thank you...

  • You use some js library like jQuery, Angularjs etc..., it is easier to help you. Ex: in jquery you can use $("#id-elemento").css("margin-left");

  • unfortunately no, I would like to know how to do with pure javascript...

  • Miguel’s example below is perfect.

1 answer

6


To fetch css properties from the stylesheets (*.css):

var myImg = document.getElementById("my-img");
var marLeft = getComputedStyle(myImg).getPropertyValue("margin-left");
alert(marLeft);
#my-img {
  margin-left: 20px;
}
<img id="my-img" src="https://laravel.com/assets/img/laravel-logo.png">

Note that getComputedStyle() serves to fetch the style of the widget from the external css file ( stylesheets). Here a has comparison between the methods:

var myImg = document.getElementById("my-img");
var marLeft = getComputedStyle(myImg).getPropertyValue("margin-left");
var marTop = myImg.style.marginTop;
alert('margin left (ficheiro externo): ' +marLeft);
alert('margin top (inline): ' +marTop)
#my-img {
  margin-left: 20px;
}
<img id="my-img" style="margin-top:34px;" src="https://laravel.com/assets/img/laravel-logo.png">

  • Great example !

  • Thank you very much for your reply!

  • No @Drkill32. I enriched the answer a little more. With a comparison between methods

Browser other questions tagged

You are not signed in. Login or sign up in order to post.