jQuery make variable out of element before appending to DOM

append, jquery, store, string, variables

Solution

`.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());
});​

Problem

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); ```

Original source