How to target the img element in JavaScript to change img src.
<body>
<div class="cover">
<img src="img.jpg" width="60" height="60">
</div>
</body>
How to target the img element in JavaScript to change img src.
<body>
<div class="cover">
<img src="img.jpg" width="60" height="60">
</div>
</body>
document.querySelector(".cover img").src = "/test/test.jpg";
please visit HTML DOM querySelector() Method for more information (compatibility, ...)
element.querySelector('img')
can get you there as well.
var cover = document.getElementsByClassName('cover')[0],
img = cover.querySelector('img');
img.src = 'http://placehold.it/60x60';
<div class="cover">
<img src="img.jpg" width="60" height="60">
</div>
First select you parent class and then using that select your child element.
var a = document.querySelector(".cover");
var b = a.querySelector("img");
b.style.width = "500px";
b.style.height = "500px";
b.src = "https://source.unsplash.com/category/nature";
If you do not want to support legacy browsers you can do with with document.querySelector:
document.querySelector(".cover img").setAttribute("src", "anotherimage.png");