JQuery: .attr value is not a function

I have this on my page:

$('#category_sorting_form_save').click(function(){ var elements = $("#category_sorting_elements > div"); $.each(elements, function(key, value) { console.info(key," : ",value); console.info("cat_id: ",value.attr('cat_id')); }); }); 

And when it is executed, I get:

 0 : <div class="dragable" cat_id="6" value="" style="opacity: 1;"> value.attr is not a function console.info("cat_id: ",value.attr('cat_id')); 

What am I doing wrong here? I am trying to get the value of a div.cat_id element.

Thank:)

Eric

+49
javascript jquery
Nov 06 '10 at 19:47
source share
3 answers

The contents of this jQuery object are simple DOM elements that do not respond to jQuery methods (e.g. .attr ). You need to wrap the value of $() to turn it into a jQuery object in order to use it.

  console.info("cat_id: ", $(value).attr('cat_id')); 

or just use the DOM method directly

  console.info("cat_id: ", value.getAttribute('cat_id')); 
+87
Nov 06 '10 at 19:51
source share

You are dealing with a raw DOM element .. you need to wrap it in a jquery object

 console.info("cat_id: ",$(value).attr('cat_id')); 
+5
Nov 06 '10 at 19:51
source share

The second parameter to the callback function passed to each () will contain the actual DOM element, not the jQuery wrapper object. You can call the getAttribute () method of an element:

 $('#category_sorting_form_save').click(function() { var elements = $("#category_sorting_elements > div"); $.each(elements, function(key, value) { console.info(key, ": ", value); console.info("cat_id: ", value.getAttribute('cat_id')); }); }); 

Or wrap the element in a jQuery object yourself:

 $('#category_sorting_form_save').click(function() { var elements = $("#category_sorting_elements > div"); $.each(elements, function(key, value) { console.info(key, ": ", value); console.info("cat_id: ", $(value).attr('cat_id')); }); }); 

Or just use $(this) :

 $('#category_sorting_form_save').click(function() { var elements = $("#category_sorting_elements > div"); $.each(elements, function() { console.info("cat_id: ", $(this).attr('cat_id')); }); }); 
+2
Nov 06 '10 at 19:55
source share



All Articles