Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: value.attr is not a function

People also ask

How to get value from attr in jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

How to add attr in jQuery?

You can add attributes using attr like so: $('#someid'). attr('name', 'value'); However, for DOM properties like checked , disabled and readonly , the proper way to do this (as of JQuery 1.6) is to use prop .

How to get attribute data in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to find the data-id attribute of an HTML element.

How to find attribute name in jQuery?

To get the name, you'd use $(selector). attr('name') which would return (in your example) 'xxxxx' .


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'));

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

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

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'));
    });
});

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

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