emilywhou
emilywhou

Reputation: 354

Element created using document.createElement() then setting id is undefined using document.getElementById() later

Please see this https://jsfiddle.net/vpLbvp0o/17/ for an example of what my issue is.

I am trying to create audio elements dynamically, layering music on the html page. Here is what I am doing when creating a new audio element and playing the music:

const new_layer = document.createElement("audio");
new_layer.id = "hello";
new_layer.src = "some_sound.mp3";
new_layer.play();

This works and the music starts to play. Later, if I want to reference this same element using its id that I have set to pause the music or update the src, using document.getElementById("hello") returns null. The element cannot be found, but the music is still obviously playing in the DOM. How do I reference this element that I have obviously created and is still there? In the jsfiddle, you can see that I am waiting with a timeout before trying to retrieve the element, but it seems like it's just not there.

If I do the same thing with an element that was already defined in the HTML document, then everything works fine. Is this a limitation of dynamically creating elements using JavaScript?

Upvotes: 1

Views: 1373

Answers (2)

Thum Choon Tat
Thum Choon Tat

Reputation: 3090

document.getElementById gets element with specified id from document, and you did not append it to the document

const player = document.createElement("AUDIO");
player.setAttribute("id", "hello");
player.src = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3";
player.play();
console.log(player.id);
console.log(player);

document.body.appendChild(player);

let get_player;
let audio_list;
setTimeout(function() {
	get_player = document.getElementById("hello");
	audio_list = document.getElementsByTagName("audio"); 

  console.log(get_player);
  console.log(audio_list);
}, 1000);

// Try pausing and playing the audio element. It does not work.
setTimeout(function() { get_player.pause(); }, 5000);
setTimeout(function() { get_player.play(); }, 10000);
<audio id="ambient"></audio>
<audio id="background"></audio>

Upvotes: 0

bc1105
bc1105

Reputation: 1270

The node isn't in the DOM, you need to add it.

document.body.appendChild(new_layer);

Upvotes: 5

Related Questions