List sharing in jQuery - memory awareness and reuse

I am trying to write a function in jQuery that will separate lists - or indeed, any element with children - that is aware of memory usage and is common enough to be widely reused, but I am having trouble resolving these against each other.

For the argument (and to keep the code at a point), let's say I'm trying to split the list into two lists after element three. I do not check my code for syntax errors or anything else - I hope you get an idea of ​​what I'm trying to do.

Option one is to write a function like this:

var list = $('ul.listCopy'); var newList = $('<ul class="listCopy" />'); var latterElements = list.children('li:gt(3)').remove(); newList.append(latterElements); list.after(newList); 

This is great, but only works as long as I know the type and attributes of the element. I would have to write a separate function if I split a div with multiple divs inside, or OL, or something else. If an element has a class or role or any other html attribute, I want to be able to copy it without worrying about which user attributes may occur in the future. I want to make this general sufficient to handle any item. This is the second option:

 var list = //something var newList = list.clone(); newList.children(':lt(4)').remove(); list.children(':gt(3)').remove(); 

It is quite common that I can make a copy of everything, but the problem is that I make a copy of the whole list. If I need to use this program to split a particularly long list, I worry about the effects of memory.

The ideal thing I would like to do is make a copy of the element, but only copy the element itself, not one of its children. I do not want to copy everything that I am going to delete. Is there a way to do something like this? Most of the plugins and features I've seen choose one way or another.

Thanks!

+4
source share
1 answer

Use your own cloneNode() method . If you do not pass true as an argument, it does not clone any children.

Example: http://jsfiddle.net/4rYxE/

  // Original element var list = $('ul'); // Clone of original (top level only) var newList = list[0].cloneNode(); // Append children greater than index 3 to the new element list.children(':gt(3)').appendTo(newList); 

Using .appendTo() removes the items from the original list and moves them to a new location (in this case, newList ).

+1
source

All Articles