zacchi4k zacchi4k - 1 year ago 57
HTML Question

Uncaught TypeError: Cannot set property 'className' of null when trying to execute script

I have an image (id="image1") and an tag (id="image1_tb") which acts like a switch for changing the class of the image.
Since I'm going to add other images, I set the href attribute of the tag to "javascript:changeClass(image1)" and created a javascript scipt which looks like this:

function changeClass(id) {
if (document.getElementById(id).className == 'swb') {
document.getElementById(id).className = 'swthb';
document.getElementById(id+'_tb').innerHTML = 'Class 1'
} else {
document.getElementById(id).className = 'swb';
document.getElementById(id+'_tb').innerHTML = 'Class 2'

but when I try to call it by clicking the text or via the Chrome dev console, nothing happens. It turns out the console outputs an "Uncaught TypeError: Cannot set property 'className' of null". If I manually replace "id" with the actual image id, it works.
What am I doing wrong?

Answer Source

Change the href from:




Without the quotes in javascript means you are trying to reference a variable. As image1 wasn't defined as a variable previously, it is null, and document.getElementById(null) is null too!