Reputation: 13213
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)
?
Upvotes: 2
Views: 96
Reputation: 82584
$('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
Upvotes: 8
Reputation: 322462
$(":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.
Upvotes: 1
Reputation: 179046
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 );
Upvotes: 1
Reputation: 34855
$('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/
Upvotes: 1