Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot append parsed string to dom

I'm using DOMParser to parse a string with and html tag to append it on another dom node

  window.addEventListener("load",carga);
  var origen = document.getElementById('origen');
  var destino = document.getElementById('destino');

  function carga(e){
    origen.addEventListener('dragstart',function(e){
        e.dataTransfer.setData("Text",origen.outerHTML);
    },false);

    destino.addEventListener('dragover',function(e){
        e.preventDefault();
    });


    destino.addEventListener('drop',function(e){
        e.preventDefault();
        console.log( e.dataTransfer.getData("Text"));
        var parser = new DOMParser();
        dragged = parser.parseFromString( e.dataTransfer.getData("Text") , "text/html");
        console.log(dragged);
        destino.appendChild(dragged);
    },false);
  }

The content of dragged variable is :

<section draggable="true" id="origen" style="height: 50px; width: 50px; border-color: green; border-style: solid;">origen</section>
like image 665
af_imi4 Avatar asked May 11 '26 19:05

af_imi4


1 Answers

Actually when you use DOMParser's parseFromString() method with the option text/html it will return a HTMLDocument and not a DOM element. So you can't directly append the result to an element, that's why you got TypeError: Argument 1 of Node.appendChild is not an object.

You need to get the content of this HTMLDocument before appending it to your Element, this is how you should implement it:

var parser = new DOMParser();
var dragged = parser.parseFromString( "<div><p>foo</p><p>bar</p></div>" , "text/html");

var divDoc = dragged.getRootNode();
destino.appendChild(divDoc.body);

Demo:

This is a working Example:

var parser = new DOMParser();
var dragged = parser.parseFromString( "<div><p>foo</p><p>bar</p></div>" , "text/html");

var divDoc = dragged.getRootNode();
document.body.appendChild(divDoc.body);
like image 108
cнŝdk Avatar answered May 13 '26 09:05

cнŝdk