1

I would like to change the audio element I inserted with another audio element.

I checked the solution at: Create Audio element dynamically in Javascript, and I don't understand why my code isn't working.

In HTML I have:

<audio id="sound" src="shush1.mp3" controls>
    Your Browser Does Not Support the Audio Feature
</audio>

and in babySounds.js I have:

var sound = document.createElement('audio');
sound.src = "Shush2.mp3";
sound.controls = "controls";
document.getElementById("sound").appendChild(sound);
3
  • 1
    I'm not familiar with <audio>, but I would assume it's not working because you are nesting the tags with your appendChild(), such that you have <audio id="sound" src="shush1.mp3" controls\> Your Browser Does Not Support the Audio Feature <audio src="Shush2.mp3" controls="controls"></audio></audio\>. You probably want to replace the original instead. Commented Feb 6, 2023 at 14:30
  • 1
    You're appending a new audio element to the existing one. Did you mean to replace the existing one with the new one instead? Commented Feb 6, 2023 at 14:31
  • 1
    Try using replaceWith like this document.getElementById("sound").replaceWith(sound)? Commented Feb 6, 2023 at 14:32

1 Answer 1

2

Your code attempts to append your new audio element as a child of the one that's already there (appendChild), rather than replacing it.

If you want to replace it, you can use the replaceWith method instead in all non-obsolete browsers:

const sound = /*...*/;
document.getElementById("sound").replaceWith(sound);`

But if you just want to change what the sound is, you can assign to the existing element's src property instead, there's no need to create a whole new element:

document.getElementById("sound").src = "Shush2.mp3";

From the spec:

If a src attribute of a media element is set or changed, the user agent must invoke the media element's media element load algorithm.

...

The src IDL attribute on media elements must reflect the content attribute of the same name.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.