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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm following the green-checked answer here stackoverflow.com/questions/8437352/… because the HTML is encoded. It seems to be perfectly valid once its decoded (it appends just fine). Is that not correct?
You put your id in the wrong place. should be &lt;div id="newDiv"&gt; hello &lt;/div&gt;
edited with the html decode option you wanted. tested '&lt;div id="newDiv"&gt; world &lt;div id="innerDiv"&gt;!&lt;/div&gt;&lt;/div&gt;' too.
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.