Monday 3 December 2012

Remove Elements Without Deleting Data in jquery



The new ".detach()" method allows you to remove elements from the DOM, much like the ".remove()" method. The key difference with this new method is that it doesn’t destroy the data held by jQuery on that element. This includes data added via ".data()" and any event handlers added via jQuery’s event system.

This can be useful when you need to remove an element from the DOM, but you know you’ll need to add it back at a later stage. Its event handlers and any other data will persist.




var foo = jQuery('#foo'); 
// Bind an important event handler 
foo.click(function(){ 
    alert('Foo!'); 
}); 
foo.detach(); // Remove it from the DOM 
// … do stuff 
foo.appendTo('body'); // Add it back to the DOM 
foo.click(); // alerts "Foo!"

jquery Everything “until”!

Three new methods have been added to the DOM traversal arsenal in 1.4, "nextUntil", "prevUntil" and "parentsUntil". Each of these methods will traverse the DOM in a certain direction until the passed selector is satisfied. So, let’s say you have a list of fruit:



  1. <ul>  
  2.     <li>Apple</li>  
  3.     <li>Banana</li>  
  4.     <li>Grape</li>  
  5.     <li>Strawberry</li>  
  6.     <li>Pear</li>  
  7.     <li>Peach</li>  
  8. </ul>
 You want to select all of items after "Apple", but you want to stop once you reach "Strawberry". It couldn’t be simpler:


  1.  jQuery('ul li:contains(Apple)').nextUntil(':contains(Pear)');