How to insert HTML as Text

前端 未结 5 1652
无人及你
无人及你 2020-12-09 20:03

I want HTML, for example,

, to show show as just that, in plain text, and not interpreted by the browser as an actual tag.

I know JQuery has .h

相关标签:
5条回答
  • 2020-12-09 20:41

    This is a job for the method createTextNode

    var target div = document.getElementById('div1');
    targetDiv.appendChild(document.createTextNode('<p>HelloWorld</p>'));
    
    0 讨论(0)
  • 2020-12-09 20:43

    There's no need to escape the characters. Simply use createTextNode:

    var text = document.createTextNode('<p>Stuff</p>');
    document.body.appendChild(text);
    

    See a working example here: http://jsfiddle.net/tZ3Xj/.

    This is exactly how jQuery does it (line 43 of jQuery 1.5.2):

    return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
    
    0 讨论(0)
  • 2020-12-09 20:45

    The function used by Prototype looks like a good start:

    http://www.prototypejs.org/api/string/escapeHTML

    function escapeHTML() {
        return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
    }
    

    Version more suited to use outside Prototype:

    function escapeHTML(html) {
        return html.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
    }
    
    0 讨论(0)
  • 2020-12-09 20:47

    i suggest to use pre tag of html

    and you can convert your using this link

    e.g if you copy

    <p>Hi </p>
    

    it will give you converted code as...

    &lt;p&gt;Hi &lt;/p&gt;
    

    Just copy and paste above code in pre and it will work fine...

    0 讨论(0)
  • 2020-12-09 21:02

    You can use aslo innerText from most of DOM elements:

    document.getElementById('some').innerText = "There can be <b> even HTML tags </b>";
    

    The tags will not be formatted. You can aslo use \n for new line and more codes (\t, \u2623...). If you want aslo to use fixed-size characters you can use easy <pre> tag.

    0 讨论(0)
提交回复
热议问题