user290043
user290043

Reputation:

jQuery: value.attr is not a function

I have this snipped in 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 the div.cat_id element.

Upvotes: 96

Views: 143351

Answers (5)

Abdulkarim Kanaan
Abdulkarim Kanaan

Reputation: 1763

I think this is the simplist one:

$("element").getAttribute("<attribute_name>")

if you want to set a value to an attribute

$("element").setAttribute("<attribute_name>", "<new_value>")

Upvotes: 3

Eduardo
Eduardo

Reputation: 527

You can also use jQuery('.class-name').attr("href"), in my case it works better.

Here more information: "jQuery(...)" instead of "$(...)"

Upvotes: 1

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263017

The second parameter of the callback function passed to each() will contain the actual DOM element and not a jQuery wrapper object. You can call the getAttribute() method of the 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 simply 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'));
    });
});

Upvotes: 5

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196092

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

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

Upvotes: 11

kennytm
kennytm

Reputation: 523454

Contents of that jQuery object are plain DOM elements, which doesn't respond to jQuery methods (e.g. .attr). You need to wrap the value by $() to turn it into a jQuery object 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'));

Upvotes: 184

Related Questions