0

Possible Duplicate:
Getting jQuery-inserted DOM elements without requerying for element after insertion

Is there a way to store a newly prepended element (with jQuery) into a var?

I want to do something like this:

var new_div = $('#my-div').prepend('<div>Something new</div>');

setTimeout(function () {
    new_div.remove();
}, 2000);
Community
  • 1
  • 1
EsTeGe
  • 2,975
  • 5
  • 28
  • 42
  • This question has been answered here: http://stackoverflow.com/questions/3655627/jquery-append-object-remove-it-with-delay – DeweyOx Jul 20 '12 at 15:18
  • Also having a look at the documentation helps: http://api.jquery.com/category/manipulation/dom-insertion-inside/ – Felix Kling Jul 20 '12 at 15:22

3 Answers3

2

In order to store the newly created div in your variable, you have to start with the creation of the div, then use prependTo:

var new_div = $('<div>Something new</div>').prependTo('#my-div');

setTimeout(function () {
    new_div.remove();
}, 2000);
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
1
var newItem = $('<div>Something new</div>');
new_div.prepend(newItem);

setTimeout(function () {
    newItem.remove();
}, 2000);

Assuming new_div is a jquery object in the DOM ( like another div)

Working sample : http://jsfiddle.net/exQTa/

Shyju
  • 214,206
  • 104
  • 411
  • 497
0
var new_div = $('<div>Something new</div>');

$('#my-div').prepend(new_div);

var timer = setTimeout(function () {
    new_div.remove();
}, 2000);

Or more jQuery'ish:

$('<div>Something new</div>').prependTo('#my-div').delay(2000).queue(function() {
    $(this).remove(); 
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388