Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery make variable out of element before appending to DOM

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);
like image 914
technopeasant Avatar asked Dec 19 '12 23:12

technopeasant


People also ask

How to insert content before and after elements in a jQuery?

JQuery provides various methods to insert elements at various locations. The after ( content ) method insert content after each of the matched elements where as the method before ( content ) method inserts content before each of the matched elements. Here content is what you want to insert. This could be HTML or simple text.

How do I append elements to text using jQuery?

The elements are created with text/HTML, jQuery, and JavaScript/DOM. Then we append the new elements to the text with the append () method (this would have worked for prepend () too) : var txt2 = $ ("<p></p>").text("Text."); // Create with jQuery txt3.innerHTML = "Text."; The jQuery after () method inserts content AFTER the selected HTML elements.

What is the difference between append () and prepend () methods in jQuery?

The jQuery append () method inserts content AT THE END of the selected HTML elements. $ ("p").append("Some appended text."); The jQuery prepend () method inserts content AT THE BEGINNING of the selected HTML elements.

How do you prepend text in jQuery?

The jQuery prepend () method inserts content AT THE BEGINNING of the selected HTML elements. $ ("p").prepend("Some prepended text."); In both examples above, we have only inserted some text/HTML at the beginning/end of the selected HTML elements.


2 Answers

.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());
});​
like image 83
Jason Towne Avatar answered Sep 30 '22 17:09

Jason Towne


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.
like image 21
regulatethis Avatar answered Sep 30 '22 19:09

regulatethis