-3

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.!

  • 2
    Because `>` isn't valid HTML? (At least that's my understanding... please correct me if I'm wrong) – freefaller May 07 '21 at 11:53
  • What are you trying to achieve by using `>`? – freefaller May 07 '21 at 11:54
  • I think your problem might be because you're trying to put `>` inside a `
    `. If you put other text instead of `>` then your code should work, as long as you don't have any other syntax errors.
    – JSman225 May 07 '21 at 11:56
  • Does this answer your question? [How to display HTML tags as plain text](https://stackoverflow.com/questions/6817262/how-to-display-html-tags-as-plain-text) – Reyno May 07 '21 at 11:57
  • If you just want to put `>` into the container, you could just do -> `innerText = '>'` – Keith May 07 '21 at 12:00
  • What purpose would it serve to have it in there? A DOM node has children for which the docs say "Child nodes include elements, text and comments" ([source](https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes)). Trying to add `>` apparently resolves to neither of those three, and it seems to get discarded instead. – Peter B May 07 '21 at 12:01

1 Answers1

2

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.

T J
  • 42,762
  • 13
  • 83
  • 138
  • 1
    For people that wanna know: `lt` means `lesser than` and `gt` means `greater than` – Reyno May 07 '21 at 11:59
  • @Reyno it's `less than` https://stackoverflow.com/questions/5068951/what-do-lt-and-gt-stand-for https://ell.stackexchange.com/a/821/55055 – freedomn-m May 07 '21 at 12:03
  • 1
    If you want to do the escape the html in code, you can use the DOM to do it for you.. eg. `const escHtml = s => { const a = document.createElement('div'); a.innerText = s; return a.innerHTML; }` – Keith May 07 '21 at 12:09