1

I'm using this code to generate a div dynamically:

// my html string :)
var myString = '<id="newDiv"div> hello </div>';

// html decode the string    
myString = $("<div />").html(myString).text();

// appending the string
$("#parentDiv").append(myString);

It appends just fine (it shows up on the screen). And also doing $('#newDiv').length correctly shows a value of 1. But then when I try to call remove() on it (or any function) like

$('#newDiv').remove()

nothing happens. What is going on?

zakdances
  • 22,285
  • 32
  • 102
  • 173

2 Answers2

3

there is a bit of extra work there. and the &lt;id="newDiv"div&gt; hello &lt;/div&gt; is actually <id="newDiv"div> hello </div> which is not normal html to my understanding.

//here is what I think you wanted:
    $('<div id="newDiv">hello</div>').appendTo("#parentDiv");
    alert($("#newDiv").length);
    $("#newDiv").remove();

edit - decode the html text, then attach it:

var emptyDivNeverAppendedToDom = $('<div/>');
//per the other so.com question
    var html = emptyDivNeverAppendedToDom.html('&lt;div id="newDiv"&gt; world &lt;/div&gt;').text();
//just being verbose.
    var elem = $(html);
    //the actual work
    elem.appendTo("#parentDiv");
    //elem.remove();

a js fiddle uncomment the elem.remove() lin to watch it work.

DefyGravity
  • 5,681
  • 5
  • 32
  • 47
  • I'm following the green-checked answer here http://stackoverflow.com/questions/8437352/jquery-append-html-string-as-html/8437392#8437392 because the HTML is encoded. It seems to be perfectly valid once its decoded (it appends just fine). Is that not correct? – zakdances Dec 09 '11 at 18:55
  • You put your id in the wrong place. should be `<div id="newDiv"> hello </div>` – fehays Dec 09 '11 at 19:05
  • edited with the html decode option you wanted. tested `'<div id="newDiv"> world <div id="innerDiv">!</div></div>'` too. – DefyGravity Dec 09 '11 at 19:44
0

Works great as soon as you put the id at the right place :

var myString = '&lt;div id="newDiv"&gt; hello &lt;/div&gt;';

http://jsfiddle.net/NN9v2/1/

dammoer
  • 16
  • 3