Reputation: 99
I am trying to use a button to change a picture on my webpage. When assigning a new value to the src
attribute I have below error
Unable to set property 'src' of undefined or null reference
My code is below:
<nav>
<ul class="menuitem">
<li><a href="#Introduction">Introduction</a></li>
<li><a href="#Experience">Experience</a></li>
<li><a href="#Skills">Skills</a></li>
<li><a href="#Courses">Courses</a></li>
<li><a href="#Links">Links</a></li>
<li><a href="#Contact">Contact</a></li>
</ul>
<id ="navImg">
<img src="C:\Users\toffy\Desktop\Course\CMP\Web-based\Worksheets\Tools\cat-selfie.jpg" alt="CatSelfie"style="width:125px;height:75px;" />
</id>
<button type="button" onclick="imgUpdate()">Another image</button></button>
<script>
function imgUpdate(){
document.getElementById("navImg").src="C:\Users\toffy\Desktop\Course\CMP\Web-based\Worksheets\Tools\foo.jpg";
}
</script>
</nav>
Upvotes: 1
Views: 2737
Reputation: 7753
After cleaning up a bit of your HTML, the JavaScript code works as expected
function imgUpdate(){
var img = document.getElementById("navImg"); img.src="https://i.sstatic.net/6UgUs.jpg?s=328&g=1";
}
<nav>
<ul class="menuitem">
<li><a href="#Introduction">Introduction</a></li>
<li><a href="#Experience">Experience</a></li>
<li><a href="#Skills">Skills</a></li>
<li><a href="#Courses">Courses</a></li>
<li><a href="#Links">Links</a></li>
<li><a href="#Contact">Contact</a></li>
</ul>
<img id="navImg" src="https://www.gravatar.com/avatar/058c57b7a3c00e7d4e8a010ace61889a?s=32&d=identicon&r=PG&f=1" alt="CatSelfie"style="width:125px;height:75px;" />
<button type="button" onclick="imgUpdate()">Click for another image</button>
Upvotes: 1
Reputation: 360672
You can fix it by not making up your own HTML tags. <id>
is not a valid html tag, period. ID is an ATTRIBUTE for a tag, it is not tag itself:
<img id="navImg" ...>
And even if it WAS a tag, you'd be setting the src
of the <id>
tag, not the img, and effectively have
<id =navImg src="...">
Upvotes: 2