16

I'm trying to append this string:

<div> hello </div>

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.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
zakdances
  • 22,285
  • 32
  • 102
  • 173

3 Answers3

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

Community
  • 1
  • 1
Timothy Khouri
  • 31,315
  • 21
  • 88
  • 128
  • What happens if there is complex nested divs inside the outer div instead of just the text "hello"? – zakdances Dec 08 '11 at 20:45
  • Is there a way to register the new html as a jquery node so it can be referenced as such (like with $('#newDiv' )? – zakdances Dec 09 '11 at 17:47
  • Thanks!! That Saved Me! Btw I used to to append text dynamically in jquery cleditor http://premiumsoftware.net/cleditor/ – normalUser Aug 25 '14 at 14:19
0

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.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Kevin M
  • 1,524
  • 17
  • 38
-1

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);
jamesmillerio
  • 3,154
  • 4
  • 27
  • 32
  • 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 `
    ...` node).
    – Andreas Covidiot Oct 18 '21 at 06:45