Why am I getting 0 (zero) when accessing a numeric attribute of a nodelist generated by getElementsByTagName?

StackOverflow https://stackoverflow.com/questions/21177773

  •  29-09-2022
  •  | 
  •  

Question

Why can I not get any of the numeric attributes?

My code is as follows:

var img = document.getElementsByTagName("img");  
console.log( "\'img[0].namespaceURI\' results in " + img[0].namespaceURI );
console.log( "\'img[0].height\' results in " + img[0].height );
console.log(img);

Strings work. But none of the numeric values...

See image enter image description here

Was it helpful?

Solution 2

Most likely the image hasn't fully loaded yet. Use an onload handler.

var img = document.getElementsByTagName("img")[0];  
img.onload = function() {
    console.log( "\'img[0].namespaceURI\' results in " + this.namespaceURI );
    console.log( "\'img[0].height\' results in " + this.height );
    console.log(this);
};

If there's a possibility that the image is cached, then you can check its .complete property and invoke the handler manually if needed.

if (img.complete) 
    img.onload();

OTHER TIPS

The outline of an DOM element in the console reflects the state it has when you click on the arrow to show the outline (depending on the version of the browser its content is also updated when the dom changes while the outline is open). console.log(img); logs reference to the element not the state of the element at the time where you call console.log(img);

While the console.log of img[0].height shows the value of height of the image at the time where you do the logging, because you request the height directly and because it is a primitiv. So if the image is not loaded at that time the height shown when you call console.log(img[0].height) is 0.

You need to wait until the images is loaded to get its calculated values.

This behavior for console.log / console.dir is the same for all non primitives. Object, Arrray, DOMElements, ... are passed as reference to the console. String, Numbers, Bools are passed by value to the console output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top