9

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);
technopeasant
  • 7,809
  • 31
  • 91
  • 149
  • Some of these examples may or may not be useful to you: http://stackoverflow.com/a/12009839/84206 – AaronLS Dec 20 '12 at 00:04

2 Answers2

13

.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());
});​
Jason Towne
  • 8,014
  • 5
  • 54
  • 69
2

Not sure exactly what you're trying to do here but if you want to save the result of a jQuery selector, you'd do it just like you would any other variable:

var gallery = $("#rGallery");

If you want to create a new element and save it:

var gallery = document.createElement("section");
// Do other stuff on it, like set attributes, etc.
regulatethis
  • 2,322
  • 14
  • 17