Is it a mandate to append an element created by javascript to a parent node

This may seem silly question but I seek clarification since my application is very huge.

I have:


var audio = document.createElement("audio");

Do I have to always append this element to a parent node like:


document.body.appendChild(audio); // or something

Is it necessary since I remove and create the audio element on the fly base on a handler function or user interaction?

My current practice is that I never append them to anything. Is this a good practice?

Note: I do this because there is no current browser supports switching audio API source node natively. It can be done through hack.

Thank you,

You have to append your code somewhere in the DOM, otherwise it will only live in the variable in Javascript and not be accessible by the browser’s rendering engine.

Thank you so much. This is very clear answer. I’ve also noticed that changing practice in JavaScript bring a significant different performance. That’s why I ask.

Not entirely correct. You can also insert it. But yes, it needs to go into the DOM somewhere.

Thank you Mittineague. I do some research base on your suggestion. The bellow link to a (rather old) article suggests that the insert method you recommended is better a practice than appenChild.

http://www.stevesouders.com/blog/2010/05/11/appendchild-vs-insertbefore/

You’ve really made my day.