Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'pop' or 'shift' from jQuery set

Tags:

jquery

In Javascript, arrays should have methods pop and shift.

However, JQuery objects seem to be missing these methods:

$('div').shift(); // Error, shift is undefined $('div').pop(); // Error, pop is undefined $('div').splice(); // Splice is OK actually 

I wonder why these functions are missing - after all, the jquery object is just an array.

What's the easiest way of performing pop and shift functions on jquery objects?

like image 433
cbp Avatar asked Jun 29 '11 03:06

cbp


People also ask

How to pop in jQuery?

pop = function() { var top = this. get(-1); this. splice(this. length-1,1); return top; }; $.

What is $$ in jQuery?

$ sign is just a valid javascript identifier which is used as an alias for jQuery. Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it.

How do I move something in jQuery?

All you have to do is select the element(s) you want to move, then call an “adding” method such as append() , appendTo() or prepend() to add the selected elements to another parent element. jQuery automatically realises that the element(s) to add already exist in the page, and it moves the element(s) to the new parent.

What does .shift do in Javascript?

shift() The shift() method removes the first element from an array and returns that removed element.


1 Answers

They're missing because a jQuery object isn't an Array.

(function( $ ) {     $.fn.pop = function() {         var top = this.get(-1);         this.splice(this.length-1,1);         return top;     };      $.fn.shift = function() {         var bottom = this.get(0);         this.splice(0,1);         return bottom;     }; })( jQuery ); 

EDIT: .slice() doesn't modify the original object. Fixed to use .splice() instead.

like image 81
user113716 Avatar answered Sep 21 '22 14:09

user113716