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);
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.
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.
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.
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.
.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());
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With