How to grab all objects in a selector? - javascript

Like
$(":input")
How do you return each object if there are multiple inputs? Maybe in somekind of array?
Also, is it possible to return the individual objects while using $(":input").after(x) ?

jQuery each
$('input').each(function () {
$(this); // A Single Input
})
Or
$('input')[0]; // HTMLElement Input
Alternatively, jQuery's .get:
supports a little more than [...], e.g. .get(-1) returns the last
element (which can be useful) - pimvdb
How to get length: $('input').length

$('input')
will select all inputs
If you wanted to do something to them...
$('input').each(function(){
$(this).css('background','red')
})
see this http://jsfiddle.net/jasongennaro/RczBh/

the jQuery factory function, jQuery(...selector...) or $(...selector...), returns a jQuery.init object, which is essentially a fancy array of elements.
the each function is a simple way to continue to chain function calls while iterating through the entire selection of elements.
The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.
The function parameter has two parameters function( index, element ), you could use i in place of index as it has the same basic effect. this will also refer to the element, so the second parameter is largely unnecessary unless you plan on executing a function within inner scope while retaining the reference to the element.
var vals=[];
$('input').each(function(index,element){
var $this, val;
$this = $(this);
val = $this.val();
vals.push(val);
...do more stuff...
});
console.log( vals );

$(":input") // Returns a collection of DOM elements at 0-based indices wrapped
// in an object that contains jQuery methods
$(":input").length // Is used to discover the quantity of elements matched.
$(":input").after('something') // Implicitly applies .after() to each element.
// Most jQuery methods work this way.
$(":input").each(function() { // Lets you operate on each element individually.
alert( this.nodeName ); // "this" will reference the current element.
});
"Also, is it possible to return the individual objects while using $(":input").after(x)"
If you mean you want a collection of the resulting elements created by .after(), it will depend upon what x is.
If it's a single element (not a text node), just do this:
var new_elems = $(":input").after(x).next();
This places the new element after each input, then uses the next()[docs] method to traverse to the next element sibling of each input, which should be the new element that was inserted.

Related

array.eq() vs. array[] in Javascript and Jquery

When accessing an array, when is it appropriate to use the .eq() function?
For example, I have...
slides.eq(slidesLength-1).css("z-index", (slidesLength-1));
and later I have...
for(i=0; i<slidesLength-1; i++) {
$(slides[i]).css("left", "-100%");
}
In the first piece of code, the slideshow stops functioning if I don's use the .eq() function. However, the second piece seems to function whether I use the .eq() function or not. Why is this?
slides is not an array. It's a jQuery object. The .eq() method returns you the element at the specified index as a jQuery object.
While jQuery objects may not be arrays, they can pretend to be by having a length property as well as properties corresponding to the indexes. (Since they are not arrays, you can't call methods like .pop(), .forEach(), etc. on them.)
When you do slides[i], you are actually getting the DOM element, not a jQuery object. The $() function turns the DOM element into a jQuery object.
So, when you do slides.eq(1), internally jQuery is doing $(slides[i]).
P.S. Objects, like jQuery objects, that pretend to be arrays are called "array-like objects". If you console.log(slides), it may look like an array. This is just your console trying to make things convenient for you. (See this question for more info: Creating array-like objects in JavaScript)
.eq() is a jQuery method which returns a jQuery object, while accessing by index returns plain DOM element. You should use eq() when you want to use jQuery methods (css() in this case) on the returned selection.
The reason $(slides[i]) works is because you're constructing a jQuery object by passing the plain element to $() constructor.
Your slides variable is not an Array, but a jQuery object.
.eq() returns a jQuery object, eventually empty if index is out of bounds, and a negative index is counted from the end.
.get() returns a DOM Element, or undefined if index is out of bounds, and a negative index is counted from the end.
[] returns a DOM Element, or throw an Error if index is out of bounds.
...
Additionally, jQuery methods let you interact with a set of elements as it was alone. So you if you do:
slides.css("left", "-100%");
It is applied on every matched elements contained in the jQuery object. It is unnecessary to loop over them.
...
Also the preferred way to loop over matched elements is using the each() method:
slides.each(function (i, el) {
var $el = $(el);
});
...
Also it is an established convention to prefix jQuery variables with a $ sign; it let you to easily differentiate DOM elements from jQuery objects. But that's only a matter of taste.

what is prevObject and context in pushstack in jquery ?

I understand how the pushstack function works and I also understand how to use it for my plugins (I guess that's what its most used for , just for internal use and for end() to function properly and other similar methods) .
now below is the jquery source of pushstack , have a look :
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
theres a lot going on in that function really and I kind of get most part of it , but I have a small problem , understanding the below lines of code :-
ret.prevObject = this;
ret.context = this.context;
what is prevObject and context ? can somebody give me a clue , it definitely does't seem to be a javascript thing ?
Basically prevObject is used to allow flexibility for the jquery selectors chaining syntax.
Most of jQuery's DOM traversal methods operate on a jQuery object instance and produce a new one, matching a different set of DOM elements. When this happens, it is as if the new set of elements is pushed onto a stack that is maintained inside the object. Each successive filtering method pushes a new element set onto the stack
Everytime you make a new filter a new jquery instance is constructed matching your selector and the previous one is stored in it to allow the .end() and the addBack() functions to work (most of the DOM transversal functions use pushStack internally). If this property were not used every selector will forget about the previous one and it will not behave like a stack. Think parent instead of prevObject and it will make it easier to understand.
The context property is deprecated in jQuery 1.10 and only used for supporting live() method but it must be added because the returning object is constructed merging an empty jQuery constructor as first parameter and a set of elements as the second.
var ret = jQuery.merge( this.constructor(), elems );
Because .merge returns the first array modified it's context property might not have the correct value so is overwritten with the correct one this.context
Check this jsfiddle and open the console. You will see that the first value of prevObject is the document as we are making a new selector and then is the ul element since we filter using find. Moreover you can go to the last filter and lookup the whole chain of selectors up to the document again.
I recommend you to use the JQuery API instead of this property as reference in production but this will allow you for example to know the result of all the selectors that have been applied to obtain a given set of DOM elements.

Does jQuery re-query the DOM when $(this) is called?

In the following code, when $(this) is called, does jQuery re-query the DOM as though a selector has been passed to it (using some property of the object as a selector), or does jQuery retain the previously returned object?
$('.someButton').on('click', function() {
$(this).remove(); // Is this another lookup, or just a wrapper for the previously returned object?
});
It doesn't re-query the DOM, this is already an element. jQuery simply sets the context to the element, adjusts the length, and returns itself. This code is from the init function, which runs when you do $(something), this is part of a big if..else statement, where it also checks for selectors, arrays among other things:
// HANDLE: $(DOMElement)
} else if (selector.nodeType) {
this.context = this[0] = selector;
this.length = 1;
return this;
So basically it just wraps the element in a new jQuery object.

What does $('<div>').parent() return?

I'm working on a jQuery widget that attaches events to the widget's parent, but I'm unable to tell if it has a parent.
For example;
var x = $('<div>');
x.mywidget();
........... in mywidget
_create : function () {
var y = this.element.parent() === undefined ? this.element : this.element.parent();
y.bind(....);
}
I need to check if the widget has been added to the DOM before I do the bind statement. If it has not been added to the DOM, then I'll just bind this.element.bind(....) instead.
The problem is that $('<div>').parent() returns a jQuery object! I was expecting that it would return undefined.
So I'm wondering what parent could it be returning when it shouldn't have a parent?
You may use myDiv.parent().length to know if the jQuery set is empty or not.
But this will yield false positives if the object wasn't removed from the DOM directly but it parent was.
If you want a reliable detection, then, you should use jQuery.contains(document.documentElement, myDiv).
It will always return an object. If you want to see whether anythings in the object, you can check for .length == 0, so $("<div>").parent().length == 0 would be your check.
Check the length of the jQuery object returned. If your div has no parent, the jQuery object returned by .parent will wrap zero elements.
All jQuery DOM searching and manipulation methods return a jQuery collection with 0 or more elements. $("<div>").parent() returns a collection with no elements (an empty collection). You can still call any jQuery method on it, but without being tied to a DOM element what you can do is very limited. It will have .length of zero, and the callback will not be reached when iterating over with .each.
I would check the length of the jQuery object since jQuery will always return an object.
it will be always a parent, can be the body for example
use jquery data for example to set your init marker
var wasInit = ( $(this).data("mypluginwasinit") !== undefined );
if(wasInit) return;
$(this).data("mypluginwasinit","yes");

How to build a cache of the DOM that does not change

So I tried to build a cache of the DOM:
var DOM = document.getElementsByTagName('*');
However, the DOM variable seems to be a dynamic reference, so that if I change an element in the DOM, the DOM variable changes as well.
I tried iterating through the DOM variable and using the cloneNode method to create a deep copy of each node. This works in that it does not change when I change the DOM. However, the problem is that a cloned node does not equal its original DOM node when you compare them with the === operator.
So to sum up, I'm looking to create a cache of the DOM that does not change but whose nodes are still equal to the original DOM nodes.
document.getElementsByTagName returns a "live" NodeList, which isn't what you think at all. When you access the list, the DOM is traversed (implementation may cache it) every time to get the result. This gives the illusion of the list being live.
document.getElementsByTagName("div") === document.getElementsByTagName("div")
//true
To do what you want, simply convert it to an array. DOM = [].slice.call(DOM)
You seem open to a jQuery solution, so:
$("*")
will return a jQuery object containing all the elements. It will not be updated as the DOM changes.
Or if you just want elements within the <body> (i.e., not <script> or <meta> elements, etc., from the <head>) then:
$("body *")
Being a jQuery object it will of course allow you to access jQuery methods, but you can also access the DOM elements directly with array notation:
var DOM = $("body *");
DOM.show(); // example jQuery method call
alert(DOM.length); // show count of elements in DOM
alert(DOM[4].value) // example of direct access to fifth DOM element
I prefer to use the following methodology:
https://gist.github.com/3841424#file-domcache-js
Or, you may replace the DOM object with a method in this implementation:
var myNS = {
myEventHandler: function(event){
this.DOM.$el.doSomething();
},
cacheDOM: function(){
return {
$el: $("#matrix")
};
},
initialize: function(){
this.DOM = this.cacheDOM();
}
};

Categories