-4

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>
Séan Lionel
  • 1
  • 1
  • 4

4 Answers4

2
document.querySelector(".cover img").src = "/test/test.jpg";

please visit HTML DOM querySelector() Method for more information (compatibility, ...)

A.Baudouin
  • 2,855
  • 3
  • 24
  • 28
0

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>
Adam Azad
  • 11,171
  • 5
  • 29
  • 70
0

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";
frnt
  • 8,455
  • 2
  • 22
  • 25
0

If you do not want to support legacy browsers you can do with with document.querySelector:

document.querySelector(".cover img").setAttribute("src", "anotherimage.png");
thomasreiser
  • 180
  • 2
  • 13