Appending HTML-encoded string as HTML, not as text

前端 未结 3 1512
野的像风
野的像风 2020-12-10 12:21

I\'m trying to append this string:

<div> hello </div>

as an HTML node, but instead of appending HTML it just ap

相关标签:
3条回答
  • 2020-12-10 12:56
    // This is your string :)
    var myString = "&lt;div&gt; hello &lt;/div&gt;";
    
    // This is a way to "htmlDecode" your string... see link below for details.    
    myString = $("<div />").html(myString).text();
    
    // This is appending the html code to your div (which you don't have an ID for :P)
    $("#TheDivIWantToChange").append(myString);
    

    HTML-encoding lost when attribute read from input field

    0 讨论(0)
  • 2020-12-10 13:01

    You can create a new div with .createElement('div'). Then simply change the new element's HTML.

    $(document.createElement('div').html('<p>All new content.</p>'));
    

    To attach the new element to the DOM either use element.append() or .appendTo(element) to append to your element of choice.

    0 讨论(0)
  • 2020-12-10 13:11

    Maybe this is a bit verbose, but this is usually how I handle stuff like that:

    var div = $(document.createElement("div"));
    
    div.text(" hello "); //Or div.html(" hello ") if need be...
    
    $("#divtoappendto").append(div);
    
    0 讨论(0)
提交回复
热议问题