Dygerati
Dygerati

Reputation: 666

jQuery .add() using generated element not working

I'm trying to loop through an array, using it's values to create a collection of elements to later be added to the DOM.

In doing so I'm using this code:

$().add($('<span />', {
    class: 'child',
    text: 'test'
})).appendTo('.container');

Or something similar... the generated element is not added to the collection. Here's a fiddle illustrating the same: http://jsfiddle.net/Dygerati/WTYSQ/2/

Upvotes: 0

Views: 68

Answers (2)

dersvenhesse
dersvenhesse

Reputation: 6414

Just use a simple array and push the new elements to your array.

var spans = new Array();
console.log(spans.length);

spans.push($('<span />', {
    class: 'child',
    text: 'test'
}));

console.log(spans.length);   
$('.container').append(spans);

http://jsfiddle.net/WTYSQ/4/ In your posted fiddle you are also mixing the container and parent class, which is why append() doesn't work still. I named both container.

Upvotes: 1

JCOC611
JCOC611

Reputation: 19719

No need to create an empty jQuery object. Also, there was no .container in your HTML. Use this code:

var spans=$('<span />', {
    class: 'child',
    text: 'test'
});  

$('.container').append(spans);

Working jsFiddle

Upvotes: 1

Related Questions