'How to print html code tags in a specific element?

<div class="container">
    <pre>
        <code class="language-html">
            <h1>I want to display html tag</h1>
        </code>
    </pre>
    <pre>
        <code class="language-html">
            <h2>I also want to display html tag</h2>
        </code>
    </pre>
    <pre>
        <code class="language-not-html">
            <b>I dont want to display html tag</b>
        </code>
    </pre>
    <pre>
        <code class="language-css">
            html{
                margin:20x;
            }
        </code>
    </pre>
</div>

I need help on how to display my html tags in plain text inside div class="container" but only to code class="language-html" using javascript or jquery. I know that changing tags into &lt and &gt but i dont know how to do it using javascript. I dont want to hard code it also because the purpose of my website is to have textfield and a button that everytime i press the button it will make a new <pre> and <code> tags. I want to make a website with a highlight.js BTW. Thanks in advance



Solution 1:[1]

Disclaimer: I'm the current maintainer of Highlight.js.

All the answers here are dangerous in that they potentially expose you to XSS and code injection attacks. This type of encoding must be done on the server before the code hits the browser or you're just going to shoot yourself in the foot eventually when the code actually RUNS instead of just being displayed.

Having examples like this to promote this type of insecure behavior isn't good for the broader ecosystem.

The correct way to write this HTML is in escaped form:

<div class="container">
    <pre>
        <code class="language-html">
            &lt;h1&gt;I want to display html tag&lt;/h1&gt;
        </code>
    </pre>

Update: The code needs to be sent from the web server this way. You cannot run JavaScript code on the client-side to "fix" this before Highlight.js sees it. That will make the warning go away, but it will NOT fix the serious security issue.

Solution 2:[2]

First detect < and > then use replaceAll to replace them to &lt and &gt

var lang_html = document.getElementById("language-html");
            var innerhtml = lang_html.innerHTML
            if(innerhtml.includes("<")){
                innerhtml = innerhtml.replaceAll("<", "&lt;")
                lang_html.innerHTML = innerhtml
            }
            else if(innerhtml.includes(">")){
                innerhtml = innerhtml.replaceAll(">", "&gt;")
                lang_html.innerHTML = innerhtml
            }
<div id="language-html">
        <a href="www.google.com">shlok jain</a>
    </div>

Solution 3:[3]

Edit: I did not originally check the tags in your question. No where did you actually mention the use of Highlight.js in your post. I updated my response to reflect this.

I used Lodash's _.escape function to convert the literal HTML to HTML text during pre-processing.

const container = document.querySelector('.container');

const removeTextNodes = el =>
  [...el.childNodes].forEach(child => child.nodeType !== 1 && el.removeChild(child))

const format = (text, language) => {
  switch (language) {
    case 'html': return html_beautify(text);
    case 'css': return css_beautify(text);
    case 'js': return js_beautify(text);
    default: return text;
  }
}

const preProcess = code => {
  removeTextNodes(code.closest('pre'));
  const language = [...code.classList].find(cls => /language-/.test(cls));
  const [ match, lang ] = language?.match(/language-(\w+)/);
  const content = code.innerHTML.trim();
  code.innerHTML = format(lang === 'html' ? _.escape(content) : content, lang);
};

const insertCode = (e) => {
  e.preventDefault();
  const content = e.target.elements.content.value.trim();
  const language = e.target.elements.language.value;
  if (content) {
    const formatted = format(content, language);
    const pre = document.createElement('pre');
    const code = document.createElement('code');
    code.classList.add(`language-${language}`, 'hljs');
    code.innerHTML = hljs.highlight(formatted, { language }).value;
    pre.append(code);
    container.prepend(pre);
  }
}

document.forms['add'].addEventListener('submit', insertCode);
document.querySelectorAll('code[class^="language-"]').forEach(preProcess);
hljs.highlightAll();
body {
  background: #222;
  color: #EEE;
}

textarea, select {
  background: #000;
  color: #FFF;
}

textarea {
  flex: 1;
  width: 100%;
}

button[type="submit"] {
  border: #DDD;
  background: #378ad3;
  color: #FFF;
  font-weight: bold;
  padding: 0.5em;
  cursor: pointer;
  width: 10em;
}

button[type="submit"]:hover {
  background: #3CA4FF;
}

form[name="add"] {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0.25em 1em;
  flex: 1;
}

form[name="add"] * {
  margin-bottom: 0.5em;
}

.form-container {
  display: flex;
  justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.14.0/beautify.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.14.0/beautify-css.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.14.0/beautify-html.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.1/highlight.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.1/styles/a11y-dark.min.css" />
<div class="form-container">
  <form name="add">
    <textarea name="content" rows="3"><h1>Hello World</h1></textarea>
    <select name="language">
      <option value="html">HTML</option>
      <option value="js">JavaScript</option>
      <option value="css">CSS</option>
    </select>
    <button type="submit">Prepend Snippet</button>
  </form>
</div>
<div class="container">
  <pre>
    <code class="language-html">
      <h1>I want to display html tag</h1>
    </code>
  </pre>
  <pre>
    <code class="language-html">
      <h2>I also want to display html tag</h2>
    </code>
  </pre>
  <pre>
    <code class="nohighlight">
      <b>I dont want to display html tag</b>
    </code>
  </pre>
  <pre>
    <code class="language-css">
      html{
        margin:20x;
      }
    </code>
  </pre>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3