Search code examples
javascripthtmlstringdynamiccreateelement

How can I parse a string as html or maybe how can I dynamic add a complex html by clicking a button?


I need to insert this html tree when I click a button

<div class='img-wrapper'> <img id='immagine_preview' width='200px' height='200px' data-id_immagine='1'><button type='button' class='rimuoviImg' ><span class='fa fa-times'></span></button></div>

I tried this code, but it returns me a body tag with my html inside it.

     var stringToHTML = function (str) {
             
             var parser = new DOMParser();
             var doc = parser.parseFromString(str, 'text/html');
             return doc.body;
             };

I need to dynamically add the previous html elements before an upload button (I use a before() method with the stringToHTML function inside and it works). There is a simpler way to do this?. Because I learnt that the documen.createElement doesn't work with a complex argument.

Thank to all community to the help they gave me even with my previous questions.


Solution

  • You can create a html variable with template literal and inside that you can write your html semantic then you can use insertAdjacentHTML()