Search code examples
javascripthtmljquerydominnerhtml

when appending the </> text as html, it's not load into the DOM


I am trying to append the html in the DOM using innerHTML method. When </> content was inside the string html content which i want to append in DOM, It will not load in DOM. it's automatically removed.

ex:

   document.getElementById("container").innerHTML = "<div></></div>";


   console.log(document.getElementById("container").innerHTML);

   result:  "<div></div>"

I don't know why. Can anyone clarify this for me please.?

Thanks in advance.!


Solution

  • To print </> as text inside HTML, use the respective HTML codes.

    < = &lt; and > = &gt;:

    document.getElementById("container").innerHTML = "<div>&lt;/&gt;</div>";
    console.log(_.escape('</>'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.1/underscore-min.js"></script>
    <div id="container"></div>


    Common libraries like underscore/lodash has _.escape method that'll do the conversion for you. See comment by @Keith below for a custom implementation.