Hello!

Please tell me how in JavaScript (without using jQuery and other libraries) to insert such html block:

<div id="id1"> <span class="class1"> Текст1 </span> </div> 

Paste to the end of the main block:

  <div id="main"> <div id="id2"> <span class="class2"> Текст2 </span> </div> </div> 

I try to do this:

  var main= document.getElementById("main"); main.appendChild('<div id="id1"><span class="class1"> Текст1 </span> </div>'); 

But an error occurs. Apparently you need to create a DIV through CreateElement , setAttribute("id", "id1") , and then add. <span class="class1"> Текст1 </span> .InnerHTML <span class="class1"> Текст1 </span> through .InnerHTML . It is somehow difficult. Is it possible to make it easier?

Thank!

  • for this, and was invented by juikery)) - Jean-Claude
  • you createelement twice, first span, then div, insert span into it, then div in set to main, more info learn.javascript.ru/modifying-document - Jean-Claude
  • It is possible through main.innerHTML + = "<div ...>"; Many do this, but this leads to a complete update of the entire contents of the main diva, if there was a selection or an input field with information entered by the user, they will be lost. - sercxjo

1 answer 1

For example:

  var main= document.getElementById("main"); var str = '<div id="id1"><span class="class1"> Текст1 </span> </div>'; main.innerHTML += str; 
 <div id="main"> <div id="id2"> <span class="class2"> Текст2 </span> </div> </div> 

swap:

  var main= document.getElementById("main"); var str = '<div id="id1"><span class="class1"> Текст1 </span> </div>'; main.innerHTML = str + main.innerHTML; 
 <div id="main"> <div id="id2"> <span class="class2"> Текст2 </span> </div> </div>