Hello.

Tell me how to insert an HTML block with content into JS?

For example:

<div class="ds">Текст текст</div><div class="sdf12">Текст текст</div> <script type="text/javascript"> var as='<div class="ds">Текст текст</div><div class="sdf12">Текст текст</div>'; </script> 

So for some reason it does not work, but how is it correct, so that later it connects this file and it reads the markup?

    3 answers 3

    It is necessary to somehow insert the value of this variable as in the right place in the document. For example, if there is an empty <div> with a known id , then you can ( example 1 ):

     document.getElementById("mesto").innerHTML = as; 

    Or you can, for example, add a newly created <div> with your html ( example 2 ) to the end of the document, or a known element:

     var div = document.createElement("DIV"); div.innerHTML = as; document.getElementsByTagName('body')[0].appendChild(div); 

    jQuery makes the same task easier . The same two ways will look at one line:

     $("#mesto").html(as); // в элемент с id="mesto" // или $("body").append(as); // в конец документа, не оборачивая в доп. div 

    If there is a lot of HTML , in several lines, you can wrap it in a separate tag with id:

     <script id="html-1" type="text/template"> // заметьте, что это НЕ javascript! <div class="ds">Текст текст</div> <div class="sdf12">Текст текст</div> </script> <script> // а это уже нормальный JavaScript var as = document.getElementById("html-1").innerHTML; // или то же с jQuery: var as = $("html-1").html(); // а далее как всегда : ) // ... </script> 
    • one
      Thank you all, it worked. )) THANK YOU SO MUCH! - Dminko93
     <div id="ds">Текст текст</div><div id="sdf12">Текст текст</div> <script type="text/javascript"> document.getElementById("ds").innerHTML = "Текст текст"; document.getElementById("sdf12").innerHTML = "Текст текст"; </script>