HTML Attributes and JS Properties

by Mehmetcan Sinir

HTML

<body>
    <div>
        <img src="http://91ef69bade70f992a001-b6054e05bb416c4c4b6f3b0ef3e0f71d.r93.cf3.rackcdn.com/save-the-world-10061808.jpg" id="myimage" width="300" height="300">
    </div>

JavaScript

var image = document.getElementById("myimage");
//src property of the image element is equal to src attribute
/*to convert attribute name to javascript property, write it in lower case or in this form:defaultChecked*/
var imageurl = image.src;
console.log(imageurl);
console.log(image.id);

/*getAttribute, always use parseInt for numbers because attribute values are always treated as strings. Attribute names in HTML is case-insensitive*/
var width = parseInt(image.getAttribute("WiDTH"));
console.log(width);
//check out the properties of image
for(var properties in image) {
    console.log(properties);
}
image.setAttribute("width", "500");
image.width = 300;

/*for element objects "attributes" is an array-like read-only object that represents all the attributes of an element*/

console.log(image.attributes[0]);