Get rel attribute using jQuery.each

I have a list of checkboxes with different rel values. My following jquery code gives my undefined.

var checked_keys=[]; $("input[type='checkbox']:checked").each(function(index, value){ checked_keys.push( value.attr('rel') ); }); 

However, if I use "this", it works.

 var checked_keys=[]; $("input[type='checkbox']:checked").each(function(){ checked_keys.push( $(this).attr('rel') ); }); 

Can someone explain what is the difference between .each with value and .each with $ (this) ?

+5
source share
2 answers

In jQuery, the $.each method has a callback returning an index and a DOM node, and the latter is a native DOM node not wrapped in jQuery, so you need to wrap it to work with jQuery, for example attr() , otherwise you will have to use your own methods such as getAttribute('rel')

 var checked_keys=[]; $("input[type='checkbox']:checked").each(function(index, value){ checked_keys.push( $(value).attr('rel') ); }); 

As a side element, there is also a $.map method that looks more appropriate

 var checked_keys = $("input[type='checkbox']:checked").map(function(index, value){ return $(value).attr('rel'); }); 
+2
source

If you register a jQuery object, you will see that all selected elements are listed numerically in Array style.

 var domElement = jqueryObject[0];//returns the first element of the jquerycollection 

When you use the .each function, it will pass its own domElement as a value parameter, not the jQuery object of this element. This means you should wrap domElement with jquery as follows.

 $(domElement).attr('rel'); 

This makes your code look like this.

 var checked_keys=[]; $("input[type='checkbox']:checked").each(function(index, vale){ checked_keys.push( $(value).attr('rel') ); }); 
+2
source

Source: https://habr.com/ru/post/1243624/


All Articles