I want to make HTML appear as text to maybe write some snippets on a site. I know that there is a way to make < and > by using &lt; and &gt; but I would like something that were a bit easier to remember and quicker like maybe using jQuery to take the content from a snippet and turn it into regular text.

Put <pre></pre> tags around the snippet.

Put <pre></pre> tags around the snippet.

That didn't seem to work, could you give me an example?

Oops! I mixed up [code] and <pre>.

Now that I'm firing on two neurons, changing < to $lt; and > to &gt; is the only way to do it. One method:

<html>
<body>
<script lang="javascript">
  // Change all angle brackets in 'pre' tags
  function pre2Text() {
    var preElements = document.getElementsByTagName("pre");
    for (var idx=0; idx<preElements.length; idx++) {
      preElements[idx].innerHTML = preElements[idx].innerHTML.replace(/</g, "&lt;");
      preElements[idx].innerHTML = preElements[idx].innerHTML.replace(/>/g, "&gt;");
    }
  }
</script>

<h1>Auto-change angle brackets</h1>
<div>
  <p>
    <b>
      Bold
    </b>
    <i>
      italic
    </i>
      TestPre
  </p>
</div>
<pre style="width:6in; border: 1pt solid black">
  <p>
    <b>
      Bold
    </b>
    <i>
      italic
    </i>
      TestPre
  </p>
</pre>
<div>
  <p>This is a paragraph-formatted bit of text with two
    <span style="text-decoration:underline">
      underscored words
    </span>.
  </p>
</div>
<pre style="width:6in; border: 1pt solid black">
  <p>This is a paragraph-formatted bit of text with two
    <span style="text-decoration:underline">
      underscored words
    </span>.
  </p>
</pre>

<script>pre2Text();</script>
</body>
</html>

Other methods are possible. You could apply "class=snippet" to the tags you want converted, then modify the function to convert only tags that are in class 'snippet'. Or you could change the function to find [u]each[/u] tags (whatever it is) that is in class 'snippet', copy its inner HTML, convert it, put it in bordered pre tags, and append it to the inner HTML; this will automatically display both the rendered and source HTML for all tags in the snippet class.

David Flanagan's JavaScript book has all of this stuff in it (though it can take a while to understand how JS works with the DOM).

That worked very well, thank you! But could you perhaps give me an example with jQuery if you can?

Sorry, no. I've never used JQ beyond finding that it doesn't (didn't) work with my browser.

you can use text property instead of innerHTML and avoid [slow] string manipulation through js. like in:

for (var idx=0; idx<preElements.length; idx++) {
      preElements[idx].innerText=
      preElements[idx].textContent= //firefox
      preElements[idx].innerHTML ;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.