Skip to content Skip to sidebar Skip to footer

Why Do You Have To Re-select A Jquery Element From A Collection?

I have a number of check-boxes on my page, each has a name attribute for its useful value. I want to get a list of values for the checked items only. I can get a collection of elem

Solution 1:

checkedItems[i] is a raw DOM element, not a jQuery object. To get a jQuery object for a given element in the set, call checkedItems.eq(i).

You can do this more nicely by writing

var list = $(".checkbox:checked")
    .map(function() { returnthis.name; })
    .get()
    .join('\n');

Solution 2:

The code in your question is wrong, because

$(checkedItems[i].attr("name"))

should really be

$(checkedItems[i]).attr("name")

Besides that, you should really do it like this

var list = "";
checkedItems.each(function(){ list += this.name + '\n'; });

Demo at http://jsfiddle.net/dGeNR/2/


The reason it would not work, is that when you access the elements in the jQuery object with [] you get back a direct reference to the DOM element, and not another jQuery object.

Solution 3:

I presume that what you actually do is this:

list += $(checkedItems[i]).attr("name") + "\n";

checkedItems is a jQuery selection. It contains references to the elements that it contains. These elements can be manipulated by jQuery methods, or accessed directly with checkedItems[n], where n is a 0-based index.

Those properties are not jQuery selections: they are the native DOM elements. If you want to use a jQuery method like attr, you need to create a new jQuery object, wrapping that native object.

In this case, you can avoid that by using the eq method, which gets a jQuery selection from an original selection by using a numeric key:

list += checkedItems.eq(i).attr('name') + "\n";

Even better in your case would be to use a combination of map and get and Array.prototype.join:

var list = checkedItems.map(function() {
    returnthis.name;
}).get().join('\n');

Solution 4:

Well the list-building code in your question doesn't work; it should be:

for (var i = 0; i < checkedItems.length; i++)
  list += $(checkedItems[i]).attr("name") + "\n"; // or just checkedItems[i].name

The ".attr()" function is just defined to return the attribute value for the first element in the list of matched elements. It could have been designed to return an array (like the ".pluck()" function in the Prototype library), but it just doesn't work that way.

The ".css()" jQuery method is similar in that regard, as is ".val()".

Another way to do what you want is:

var list = checkedItems.map(function() {
  returnthis.name;
}).get().join('\n'); // thanks SLaks :-)

Post a Comment for "Why Do You Have To Re-select A Jquery Element From A Collection?"