0

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/

4
  • 2
    $().add ? Why this construct ? Commented Mar 26, 2013 at 19:46
  • Heres a hint: Uncaught TypeError: Cannot read property 'parent' of undefined Commented Mar 26, 2013 at 19:48
  • $('.container').append(your_new_element); Commented Mar 26, 2013 at 19:48
  • The format seems odd since it's a very simplified example of what I'm doing in my code. I'm really just wondering why the $.fn.add function doesn't work like this. Commented Mar 26, 2013 at 20:05

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I didn't realize append() took a native array. I'm still wondering why the jQuery add() function doesn't work as I expected, but I'll stop caring pretty quick.
Because add() doesn't change the original selection as you suppose. Take a closer look at the second code block: api.jquery.com/add
1

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

1 Comment

It's the add() method that I'm testing specifically, since in my actual code I'm going through a large for loop and adding elements that I generate. Then, after the loop completes, adding all to the DOM.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.