Yuriy
Yuriy

Reputation: 457

Uncaught TypeError: elements[i].attr is not a function

This is my code:

function () {
    var container = document.getElementById('data-table');
    var elements = container.getElementsByTagName("input");
    for (i = 0; i < elements.length; i++) {
        elements[i].on("ifChanged", handle_company_state(elements[i].attr('id')));
     }
}

function handle_company_state(element_id) {
    //....
}

When I'm trying to run it I' getting this error:

Uncaught TypeError: elements[i].attr is not a function

Why?

Upvotes: 2

Views: 3961

Answers (3)

Adam Azad
Adam Azad

Reputation: 11297

Use

$(elements[i]).attr()

$.attr() is jQuery method. The same fix applies for your .on() function

$(elements[i]).on("ifChanged", handle_company_state($(elements[i]).attr('id')));

And since you're using jQuery here.

You can write less.

var container = $('#data-table'),
    elements  = container.find('input'); // container is a jQuery object; thus, $.find() works as traversing method in the DOM. see http://api.jquery.com/find/

$(elements).on("ifChanged", function(){
    handle_company_state($(this).attr('id'))); // use `this` as reference to changed element.
});

Upvotes: 1

Darth
Darth

Reputation: 1650

Use getattribute method instead .attr and addEventListener instead .on. And you might not need jquery.

function () {
    var container = document.getElementById('data-table');
    var elements = container.getElementsByTagName("input");
    for (i = 0; i < elements.length; i++) {
        elements[i].addEventListener("ifChanged", handle_company_state(elements[i].getAttribute('id')));
    }
 }
function handle_company_state(element_id) {
    //....
}

Upvotes: 2

R.Costa
R.Costa

Reputation: 1393

I think you are looking for something like:

function () {
    var elements = $("#data-table input");
    for (i = 0; i < elements.length; i++) {
        $(elements[i]).on("ifChanged", handle_company_state($(elements[i]).attr('id')));
    }
}

function handle_company_state(element_id) {
    //....
}

Upvotes: 1

Related Questions