Easier way to get a jQuery object from appended element

JqueryCss SelectorsAppend

Jquery Problem Overview


Is there an easier/quicker way to get the element added using jQuery append:

How to get the $selectors element:

$container.append('<div class="selectors"></div>');
var $selectors = $('.selectors', $container);

I tried:

var $selectors = $container.append('<div class="selectors"></div>');

but that makes $selectors = $container

Maybe that's the quickest/best way. Just checking.

Jquery Solutions


Solution 1 - Jquery

Why not just:

var el = $('<div class="selectors"></div>');
$container.append(el);

?

Then you have access to 'el'.

Solution 2 - Jquery

This is my favourite way of doing it:

var $selectors = $('<div class="selectors"></div>').appendTo(container);

Solution 3 - Jquery

$selectors = $('<div/>').addClass('selectors').appendTo($container);

Solution 4 - Jquery

You could also create a new jQuery function to do it:

jQuery.fn.addChild = function(html) 
{                               
    var target  = $(this[0])                            
    var child = $(html);                                                      
    child.appendTo(target);                                                   
    return child;                                                             
};  
     

and then use it like so:

$('<ul>').addChild('<li>hi</li>');

of course if you wanted to add more than one item:

var list = $('<ul>');
list.addChild('<li>item 1</li>');
list.addChild('<li>item 2</li>');

The advantage of approaches like this is that later on you can add more to the "addChild" function if you like. Note that for both the examples above, you need to add the element to the document, so a full example might be:

$('body').addChild('<ul>').addChild('<li>hi</li>');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionslolifeView Question on Stackoverflow
Solution 1 - JquerycletusView Answer on Stackoverflow
Solution 2 - JqueryMagnarView Answer on Stackoverflow
Solution 3 - JqueryhobbsView Answer on Stackoverflow
Solution 4 - JqueryBrad ParksView Answer on Stackoverflow