Retrieve a jQuery element from an array - javascript

I am storing jQuery elements in an array, and I need to retrieve them.
I am now doing it like
var arr = [];
arr.push( $(someElement) );
Then I try to retrieve it by doing:
arr.indexOf($(someElement));
But it doesn't work as all jQuery elements look the same e.fn.e.init[1]
I'd rather not name (key) each of them because I have a lot of elements and if I could reference them similarly to how I'm trying to, it would be better for me.
How would you do it?

Why are you storing your jQuery objects in an array ? You can't save jQuery objects to preserve their states as JQuery objects are simply wrappers to the DOM elements chosen by your selector. If the DOM changes, then those changes will be reflected by the jQuery object. If you want to preserve the old values, you should store the properties you want to keep rather than the entire jQuery object. Alternatively, you could also store your jQuery string inside an array:
var arr = [];
arr.push(someElement);
When needed you can then query if your element is still contained in the array
if (arr.indexOf(someElement)){
$(someElement).dostuff......
}

Related

How to treat the return value of jQuery functions that return a bunch of elements

How to can I treat the return value of jQuery functions that would return a bunch of DOM elements. E.g. I'm using the .nextAll() function, that returns a bunch of elements, does it? Can I store the return value in a JS array? Sooner or later I want to iterate through those elements. I know there's the jQuery .each() function that would help me out here. Nevertheless, for training and understanding issues I first want to do it step by step.
I'm pretty sure, this basic question is answered somewhere, but I searched for an answer and did not find anything useful for me. Maybe I didn't find the right words. So please be kind.
jQuery functions typically returns a bunch of DOM elements, it masquerades as an array.
If you run something like:
$('p').css('background-color', 'red');
jQuery will build an array of all p elements, and then applies the css() function to each of them.
If you want a single DOM item, use get with an index:
$( "li" ).get( 0 )
So, .nextAll() also typically returns a number of elements, so it is behaving just like jQuery typically does.
each() is a handy-dandy function that operates on arrays, so it will of course operate just fine on jQuery objects:
$('li + li').nextAll().each(function(i){
//glorious code
});
You could also do this:
var nexts = $('li + li').nextAll();
$.each(nexts, function(i){
//Glorious code!!
});
Hope that makes things clearer!
You can just assign it to a variable:
var $els = $(selector).nextAll();
This way, $els will be a jQuery wrapper (array-like object) of the elements.
If you want to have an array of the elements instead, you can use
var arr = [].slice.call($els);
As the documentation of .nextall() says, it returns jQuery
A jQuery object contains a collection of Document Object Model (DOM)
elements that have been created from an HTML string or selected from a
document. Since jQuery methods often use CSS selectors to match
elements from a document, the set of elements in a jQuery object is
often called a set of "matched elements" or "selected elements".
The jQuery object itself behaves much like an array; it has a length
property and the elements in the object can be accessed by their
numeric indices [0] to [length-1]. Note that a jQuery object is not
actually a Javascript Array object, so it does not have all the
methods of a true Array object such as join().

Get multiple objects from stage by class name in KineticJS

I am using using JavaScript library Kinetic.js for HTML5 canvas.
Here is the method stage.get() to get objects from stage (canvas). I have assigned the id's or class names to each object
if I get the object by id var obj = stage.get('#obj_id') it works but If try to get the multiple objects by class name var objs = stage.get('.obj_class_name') it returns an empty [] object
How I can get multiple objects from stage .
well, you could just do .getChildren() to get all children, then iterate through the array with a loop and a condition to add a new array you created.
You can use the name attribute. It works as the classin HTML. Use the stage/layer function find('.<name>') to select all your elements with the the name <name> (The dot is necessary).

Call show on array of jQuery objects

I have a little problem concerning performance of jQuery.show.
This problem occurs in IE8 (probably also versions below, but IE8 is of my interest).
I have an array of jQuery objects, lets call it elements.
I want to show them, so i did:
for (var i = elements.length - 1; i >= 0; i--) {
elements[i].show();
}
The bottleneck seems to be the call to show. The array is already generated, so that takes no time. looping through an array should not be a problem either.
I thought of reducing this to one call to show by creating a new jQuery element containing all my elements. but I was not sure how to do this. I tried by jQuery.add.
var $elements = elements[0];
for (var i = elements.length - 1; i >= 1; i--) {
$elements = $elements.add(elements[i]);
}
$elements.show();
Now, this time it seems to be a problem with jQuery.add. Probably because it always creates a new object.
So, I thought of three different approaches that could solve my problem. Maybe you can help me with one of them:
Is there a jQuery method like add that does not return a new object, but instead adds it to the current jQuery element?
Is there an easy and fast way to create a jQuery element by an array of jQuery elements?
Is there a way to show all jQuery objects in an array in a faster way?
Answering just one of the question would probably help me out here. My problem is, that jquery always expects an array of DOM elements and not an array of jQuery elements in its methods.
Thanks a lot in advance!
-- EDIT about the contents of elements
I have a jstree that dynamically creates nodes (that is, li elements). These elements have an attribute data-id to identify them.
Now, I could always query for something like $('li[data-id=xxx]'), but this would be very slow. So instead, when li elements are created, i cache them into a dictionary like object (key is the data-id, value is the node). Out of this object, i generate my array elements. This happens very fast.
The array can have a size of up to 4000 nodes. Every jQuery Element in the array only contains one DOM-Element (li).
Edit
After reading your update, and the comments, this Very small one-liner is most likely going to be the answer:
elements.each($.fn.show);
Using the jQ each method to apply (well, internally: call is used) the show method to all elements.
The easiest, and fastest way to create a jQuery object from an array of jQuery objects would be this:
var objFromArr = $(jQarr);
I've just tested this in the console:
objFromArr = jQuery([jQuery('#wmd-input'),jQuery('#wmd-button-bar')]);
objFromArr.each(function()
{
console.log(this);//logs a jQ object
console.log(this[0]);//logs the DOMElement
});
But having said that: you say elements is an array of jQ objects, but if it's the return value of a selector ($('.someClass')) then really, it isn't: in that case, your loop is "broken":
elements = $('.someClass');
for (var i=0;i<elements.length;i++)
{
console.log(elements[i]);//logs a DOMElement, not a jQuery object
}
//It's the same as doing:
console.log(elements[0]);
//or even:
console.log($('.someClass').get(0));
But in the end, if you have an array of jQuery objects, and you want to invoke the show method on each and every one of them, I suspect this is the best take:
elements.each($.fn.show);//use the show method as callback

mootools double dollar equivalent in jquery

I have a line of code that uses mootools to get an array of elements with the given selectors
var menuItems = $$('#container .menu');
I need to convert this to jquery but can't find a solution. I have tried jQuery('#container .menu') but it doesn't return an array.
Is there a way to use '.find()' from jquery on the whole document ? (since I don't have a parent element to make it like parent.find()..)
Any other suggestion is also most welcome
With jQuery your statement:
jQuery('#container .menu')
will return a jQuery object that contains all matching elements where you can access the individual DOM elements with array-like syntax:
var menuItems = jQuery('#container .menu');
menuItems.length // gives a count of how many matched
menuItems[0] // the first matching element
// but you can also use jQuery methods on the object
menuItems.hide();
If you want an actual array rather than an array-like object you can use jQuery's .toArray() method:
var menutItemsArray = jQuery('#container .menu').toArray();
Why don't you try one of the jQuery tutorials available at the jQuery website?
If you absolutely need it as an array, rather than working with the jQuery object returned by the selector, take a look at the .toArray() function.

How to access js object properties via html element?

I have an array of objects fetched using jQuery.getJSON(). I want every one of my objects to be represented by HTML div element, so when you click the element you have access to all the properties of corresponding object. What is the best way to do it?
I wanted to do it like this:
$('.mydiv').click(function() {
var id = $(this).attr('id');
for (i=0; i<myObjectsArray.length; i++){
for (x in myObjectsArray[i]){
//..and here I got confused...
}
}
});
Is this approach any good or is there a better way to do it.
Thanks.
You can store data in the data property of your jQuery object
docs here

Categories

Resources