88

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.

slolife
  • 19,520
  • 20
  • 78
  • 121

4 Answers4

172

Why not just:

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

?

Then you have access to 'el'.

cletus
  • 616,129
  • 168
  • 910
  • 942
  • 2
    Hm. What happens if `$container` has multiple elements in this case? In my case I want to append something to all instances a selector matches and get a collection of created elements. – Rhys van der Waerden Dec 22 '14 at 01:00
  • 2
    this will not working on multiple instance of `$container` http://jsfiddle.net/onL028ty/. Use `appendTo` trick instead http://jsfiddle.net/6nmdh84e/ – ktutnik Jan 27 '15 at 08:28
66

This is my favourite way of doing it:

var $selectors = $('<div class="selectors"></div>').appendTo(container);
Magnar
  • 28,550
  • 8
  • 60
  • 65
  • 4
    +1 - mine too. Do all you need to do with the newly created element before appending it to the DOM. – Russ Cam Sep 18 '09 at 08:43
6
$selectors = $('<div/>').addClass('selectors').appendTo($container);
hobbs
  • 223,387
  • 19
  • 210
  • 288
  • 1
    Good info, thanks. It is a little verbose for me compared to the other answers, but I wonder if it does better performance wise? Performance is not an issue in my particular situation, but maybe for others. – slolife Sep 18 '09 at 16:42
3

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>');
Brad Parks
  • 66,836
  • 64
  • 257
  • 336
  • 2
    I think the last part of this answer only adds confusion; appending to the document wasn't part of the question. You could keep it real simple like cletus and have the reader imagine $container is an UL. $container.append('
  • hi
  • '); Anyways, great. Thanks. – Mike S Jun 06 '14 at 00:24