Dave's Brain

Browse - programming tips - jquery convert to from native javascript array

Date: 2010jul30
Language: javaScript

Q.  How do I convert from a jQuery object to/from a native javaScript array?

A.

Converting from a jQuery object to a native javaScript array
------------------------------------------------------------

You may not even need to do this.  You can use a jQuery object much
like an array.  For example:

	obj = $('p');	// Get all paragraphs into a jQuery object
	for (i = 0; i < obj.length; i++) {
		// Do something with obj[i]
	}

As you can see, jQuery objects have .length and [].
But, .pop() and .reverse() are missing.  And you may want to
pass the array to a function that expects a native array.  So do this:

	obj = $('p');	// Get all paragraphs

	a = $.makeArray(obj);	// One way to do it

	a = obj.toArray();	// The other way

More info:
http://api.jquery.com/jQuery.makeArray/
http://api.jquery.com/toArray/


Converting from a native javaScript array to a jQuery object
------------------------------------------------------------

Just use the jQuery() function.
For example:

	var	a, obj;

	// Make a regular javaScript array
	a = new Array();
	a.push('one');
	a.push('two');
	a.push('three');

	obj = jQuery(a);	// Now you have a jQuery object
	
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.
Advertisements: