0

I would like to convert an array of jQuery objects into a single jQuery objects with every element "after" the last created element:

Test HTML:

<div id="test">asd</div>
<a></a>

JS:

 var createElem = function(numElems) {
        var elems;
        for(var i=0; i<numElems; i+=1) {
            elems.push($("#test").clone());
        }

        return elems;

    };

    $("a").append(createElem(20)); // fails because its an array and not a jQuery object

I know that I can create an element and put all of my clones inside of it:

 var createElem = function(numElems) {
        var elem = $('<div>');

        for(var i=0; i<numElems; i+=1) {
            elem.append($("#test").clone());
        }

        return elem;

    };

But I would rather not deal with having to take out the elements from this parent wrapper before returning them.

1
  • one problem is can't append <div> to <a> is invalid html Commented Feb 3, 2013 at 23:07

4 Answers 4

2

Need to define elems as an array before you can use push

var elems=[];

EDIT: <div> is not valid child of <a>

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

2 Comments

Yes my mistake in writing it up but I still am getting this error: NOT_FOUND_ERR: DOM Exception 8
works fine here jsfiddle.net/vmec3/1... you need to do something about duplicating ID's but that won't stop code working
0

Make sure you initialize the array.

 var createElem = function(numElems) {
        var elems = [];
        for(var i=0; i<numElems; i+=1) {
            elems.push($("#test").clone());
        }

        return elems;

    };

1 Comment

first elems must be initialized as an array, which i forgot to do. But your solution throws this error: NOT_FOUND_ERR: DOM Exception 8
0

try use the append like this:

$("a").append(null,createElem(20));

according to jQuery docs (also tried this myself)

Comments

0
var createElem = function ( numElems ) {
    var $elems = $(),
        $test = $( '#test' ),
        index = 0;

    for ( ; index < numElems; index++ ) {
        $elems = $elems.add( $test.clone() );
    }

    return $elems;

};

See how that goes. I'm fairly certain that the logic is correct, I'm just unable to test this from my phone.

Comments

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.