简体   繁体   中英

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.

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.

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 (eg <p> and <div> tags can be in the array and jQuery will work as expected). See here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM