Appending HTML-encoded string as HTML, not as text

43,449
// This is your string :)
var myString = "<div> hello </div>";

// 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

Share:
43,449
zakdances
Author by

zakdances

Updated on August 12, 2020

Comments

  • zakdances
    zakdances over 3 years

    I'm trying to append this string:

    &lt;div&gt; hello &lt;/div&gt;
    

    as an HTML node, but instead of appending HTML it just appends the text:

    <div> hello </div>
    

    How do I make jQuery append this as an HTML node, not just text?

    I'd like a solution that works both for nested divs AND text, if possible.

  • zakdances
    zakdances over 12 years
    What happens if there is complex nested divs inside the outer div instead of just the text "hello"?
  • zakdances
    zakdances over 12 years
    Is there a way to register the new html as a jquery node so it can be referenced as such (like with $('#newDiv' )?
  • normalUser
    normalUser over 9 years
    Thanks!! That Saved Me! Btw I used to to append text dynamically in jquery cleditor premiumsoftware.net/cleditor
  • Andreas Covidiot
    Andreas Covidiot over 2 years
    curiously this answer helped me find what I needed although it may not be the very correct answer to this specific question, coming here from googling. the difference of x.text(...) and x.html('...') (where x.append('...') encodes like html(...)) I see as quite important for my problem (appending without encoding to some <pre><code>... node).