Reputation: 251
I want to change the images of main webpage according to the value sent in javascript file. I have defined div tag in my html file and placed default value for image src. Then I am taking input from user about their mood. Using if else, i compared the value and chose the suitable image to display on my webpage. But, I am unable to change the default value of src tag in my program. I just tried something else and could not find ways to resolve this. Thank you in advance.
NOTE: I am a beginner in JS
home.html
<!DOCTYPE html>
<html>
<head>
<title>Getting Started with</title>
</head>
<body>
<script src='script.js'></script>
<div id = 'feel'>
<img src = "images/dull.jpg">
</div>
</body>
</html>
script.js
var feelingInfo = prompt("How are you feeling? (dull or fresh or sleepy)");
var suitableImage = document.getElementById('feel');
//console.log(feelingInfo);
//Here I want to change the src
if(feelingInfo == "dull"){
suitableImage.innerHTML.src = '"images/dull.jpg">';
}
else if(feelingInfo == "fresh"){
suitableImage.innerHTML.src = '"images/fresh.jpg">';
}
else if(feelingInfo == "sleepy"){
suitableImage.innerHTML.src = '"images/sleepy.jpg">';
}
else{
console.log("Error");
}
Upvotes: 1
Views: 2747
Reputation: 5999
There are some problems in your implementation
var suitableImage = document.getElementById('feel')
you'll get the div
element not the img
element. You should be targeting img
element.suitableImage.innerHTML
is a string, so suitableImage.innerHTML.src
will be undefined, and there's no value for this statement.Get the image element and then change the src on that
const suitableImage = document.querySelector("#feel > img");
if(feelingInfo === "dull"){
suitableImage.src = "images/dull.jpg";
}
else if(feelingInfo === "fresh"){
suitableImage.src = "images/fresh.jpg";
}
else if(feelingInfo === "sleepy"){
suitableImage.src = "images/sleepy.jpg";
}
Upvotes: 1
Reputation: 9279
element.innerHTML is a string, so element.innerHTML.src does not make sense.
You should do this instead:
document.querySelector("#feel > img").src = "images/dull.jpg";
Upvotes: 2
Reputation: 1168
Simply give an id
to your img
tag - like if i give an id="feel_img"
, then using JS I can set src
like so :
if(feelingInfo === "dull"){
document.getElementById('feel_img').src = "images/dull.jpg";
}
Upvotes: 0
Reputation: 187
The problem here is that you don't query the correct tag you want to edit which is img.
First I recommend you to add an id to your picture :
<img id="picture" src="images/dull.jpg">
Then :
var suitableImage = document.getElementById('picture');
suitableImage.src = 'new src content'
Upvotes: 1