Kuba Janek Kuba Janek - 3 months ago 6
Javascript Question

can't retrieve src attribute with document.getElementById

Good day, I have a small rpoblem that I can't retrieve src html attribute out of document.getElementById

<div id="1" src="great.png">

var a = document.getElementById(1).src;
document.write(a);


gives nothing.

Answer

src is non-understand attribute for div tag. you need to use getAttribute('src')

var a = document.getElementById("1");
console.log( a.getAttribute('src') );
console.log( a.src ); // undefined
<div id="1" src="great.png">

Using img tag

var a = document.getElementById("1");
console.log( a.getAttribute('src') );
console.log( a.src );
<img id="1" src="great.png">

Comments