jmgunn87
jmgunn87

Reputation: 165

JQuery splice DOM elements

I would like to perform a splice method much like the native Array.splice but I would like to splice a jQuery collection of DOM elements. How is this done cleanly?

Edit: why do I need example code? I am looking for the exact same functionality of the ECMAScript Array.splice function, except I want it to work on a jQuery array of DOM elements, and update the DOM when it's done.

Upvotes: 0

Views: 1217

Answers (2)

redbmk
redbmk

Reputation: 4796

Selecting elements with jQuery actually gives you an array of elements, which can be treated as a normal javascript array as well as a jQuery object. To ensure that an array is a jQuery object you can wrap it in a call to jQuery(). For example:

var x = jQuery('p'),
    y = jQuery(x.splice(x.length / 2, x.length));

x.css('background-color', 'red');
y.css('background-color', 'blue');

x contains the first half of <p> tags, which all now have a red background, and y has the second half, with a blue background.

Here's some proof.

Also, there is no problem with mixing tags (e.g. <p> and <div> tags can be in the array and jQuery will work as expected). See here.

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

If you are using a DOM collection after splice of your collection you need reload the DOM with that collection to made effect the changes .

So use append and remove keywords for live changes .. which are equals to splice on an collection.

Upvotes: 2

Related Questions