skip to Main Content

I want to insert html code to a div using javascript, when i am doing this then my html code is running i just want html code not output.

document.getElementById("htmlcode").innerHTML = `<button>Click me</button>`
<span id="htmlcode">HTML code here</span>

my output:-
enter image description here
desired output something like this:-
something like this but i need Click me

2

Answers


  1. You may replace each:

     & with &amp; 
     < with &lt;
     > with &gt;
    

    And you should surround the resulting, escaped HTML code within <pre><code>…</code></pre> to:

    1. preserve whitespace and line breaks, and
    2. mark it up as a code element.

    In your case:

    document.getElementById("htmlcode").innerHTML = "<pre><code>&lt;button>Click me&lt;/button</code></pre>"
    
    Login or Signup to reply.
  2. The easiest (and probably safest) way is to use document.createTextNode.

    document.getElementById("htmlcode")
      .replaceChildren(document.createTextNode(`<button>Click me</button>`))
    <span id="htmlcode">HTML code here</span>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search