TaylorMac
TaylorMac

Reputation: 9002

How to convert an array of jQuery objects into a single object

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.

Upvotes: 0

Views: 606

Answers (4)

whitneyit
whitneyit

Reputation: 1226

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.

Upvotes: 0

charlietfl
charlietfl

Reputation: 171700

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

var elems=[];

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

Upvotes: 2

alonisser
alonisser

Reputation: 12098

try use the append like this:

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

according to jQuery docs (also tried this myself)

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

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;

    };

Upvotes: 0

Related Questions