sameold
sameold

Reputation: 19242

.before to insert multiple elements

I have an element var destination which I'm trying to insert multiple elements before it. I use .before but I use it multiple times because I'm moving multiple elements.

Is there a way to improve this code, and move all the elements at once? I'm moving an element moveElement, the element before it, and a number of other elements that have the class myClass using each(). Any way to reduce the number of destination.before()

destination.before(moveElement.prev());
destination.before(moveElement);
$('div.myClass').each(function(){
   destination.before($(this));
});

Upvotes: 0

Views: 169

Answers (1)

gdoron
gdoron

Reputation: 150253

before accepts a jquery object, so you can construct a jQuery object with all the elements.

destination.before(moveElement.prev().add(moveElement).add('div.myClass'));

add docs:

Description: Add elements to the set of matched elements.

Upvotes: 3

Related Questions