jQuery make variable out of element before appending to DOM

technopeasant picture technopeasant · Dec 20, 2012 · Viewed 11k times · Source

Trying to get efficient here. How can I store an element as a variable before appending it to the DOM? Seems like it's a waste to create it, append it, then go find it again to make a variable.

My method is below. OBV it's saving the string as a variable, not the object, but you get the idea.

Any magic for me or do I have to make two trips?

var $rGallery = '<section id="rGallery" />';

$bin.before($rGallery);

console.log($rGallery);

Answer

Jason Towne picture Jason Towne · Dec 20, 2012

.before() and .append() can take a jQuery object as a parameter. You just have to create your new object, store it in a variable and then pass it to .before() or .append().

Quick example:

<div id="bin"> </div> ​​​​​​​​​​​​​​​​​​​​

var newElement;

$(document).ready(function() {

   newElement = $("<button>New button</button>");
   $("#bin").append(newElement);

   alert(newElement.text());
});​