HTML - How to get values from a tag

5

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

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

I hope I have been clear, thank you ...

    
asked by anonymous 02.08.2016 / 14:06

1 answer

6

To get css properties from the stylesheets file (* .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">

Notethat getComputedStyle () fetches the style of the element to the external css file ( stylesheets file). Here one has a 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">
    
02.08.2016 / 14:13