user310291
user310291

Reputation: 38180

Javascript difference between document.write and DOM element.AppendChild(text)

I want to embed and show a flash file. It works fine with document.write but when I tried with AppendChild(text) it doesn't show flash but pure text instead. What DOM method to use instead ?

  <html>
  <head>
 <script>
  function addText(text,elementId){
    if (document.createTextNode){
      var mytextNode=document.createTextNode(text)
      document.getElementById(elementId).appendChild(mytextNode)
    }
  }

    </script>

  </head>

  <body>

                <div id="test">

                </div>

  <script>
      addText("<embed height='100' width='100' type='application/x-shockwave-flash' allowscriptaccess='always' wmode='transparent' quality='high' swliveconnect='true' name='test' id='test' src='test.swf'>",'test');
  </script>     
  </body></html>

Upvotes: 2

Views: 1603

Answers (2)

alex
alex

Reputation: 490213

Because you are creating a text node, not serialised HTML.

You could change the function to...

function addHTML(html, elementId) {
    if (document.createElement) {

        var holder = document.createElement('div');

        holder.innerHTML = html;

        var target = document.getElementById(elementId);

        while (holder.hasChildNodes()) {
            target.appendChild(holder.firstChild);
        }
    }
}

jsFiddle.

Upvotes: 2

kojiro
kojiro

Reputation: 77099

(function () {
    var myEmbed = document.createElement("embed");
    myEmbed.type="application/x-shockwave-flash";
    myEmbed.height='100';
    myEmbed.width='100';
    …
    document.getElementById("test").appendChild(myEmbed);
}());

At first glance such an approach can often seem unnecessarily noisy and worthless, but it integrates much more sanely with the natural syntax of HTML. If you want to be able to write HTML directly into your document, you might be happier with a framework like jQuery, which allows syntax like:

$("<embed src='…'/>")

However, if you're just doing all this to embed Flash, use swfobject.

Upvotes: 2

Related Questions