Put a bit of HTML inside a
 tag?

后端 未结 3 2079
北海茫月
北海茫月 2021-01-12 10:39

How do I put a bit of HTML inside a tag without escaping it? Or am I using an incorrect tag?

P.S. I cannot escape the HTML, it is produced by the s

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-12 11:08

    If you have no control over the emitted HTML, you can still encode it on the client side.

    Here is how you would escape all markup inside

     tags using the jQuery library:

    $(function() {
        var pre = $('pre');
        pre.html(htmlEncode(pre.html()));
    });
    
    function htmlEncode(value){ 
      return $('
    ').text(value).html(); }

    Edit: As requested, same code without using jQuery:

    function encodePreElements() {
        var pre = document.getElementsByTagName('pre');
        for(var i = 0; i < pre.length; i++) {
            var encoded = htmlEncode(pre[i].innerHTML);
            pre[i].innerHTML = encoded;
        }
    };
    
    function htmlEncode(value) {
       var div = document.createElement('div');
       var text = document.createTextNode(value);
       div.appendChild(text);
       return div.innerHTML;
    }
    

    And run the encodePreElements after the DOM has been loaded:

    
        
    Foo bar

提交回复
热议问题