-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>

2
  • 2
    And what did you try before coming here ? Commented Jul 6, 2016 at 6:18
  • 1
    This is a really basic question, you should try to google it first. Commented Jul 6, 2016 at 6:19

4 Answers 4

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

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

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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";

Comments

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");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.