Ask coding questions

← Back to all posts
Little bit of a strange issue.
AstrumDeorum (17)

So, doing a school project, and I'm not supposed to have any errors show up.
But I have one:
TypeError: Cannot set property 'volume' of null at /script.js:3:21
And the weirdest thing is that despite erroring and saying it can't do it, it does do it. I know this because I've tested the output when the line is or isn't commented.
Here's what to look at and in what files:

<audio id="CrySil" autoplay loop src="Media/CrySil.mp3" volume></audio>


var crysilVolume = document.getElementById("CrySil");
crysilVolume.volume = 0.35;

There isn't much that I see that could be wrong, but if you find anything, let me know, because I have to end with zero errors.

Answered by notGilbert (45) [earned 5 cycles]
View Answer
notGilbert (45)

It seems like you are including the script in pages without a #CrySil element

To fix this, remove the script tag from the pages without the element or check if the element exists

check if element exists

var crysilVolume = document.getElementById("CrySil");
if (crysilVolume) {
  crysilVolume.volume = 0.35
} // do things if exists
AstrumDeorum (17)

@notGilbert bro, that if statement worked. Problem vaporized.
That was way simpler than I thought.

ch1ck3n (1584)

@AstrumDeorum You can click the checkmark next to his name if it helped to reward him