Tyler Hines
Tyler Hines

Reputation: 33

"Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined" issue

function addEditButton() {
    $(".editButton").remove();
    $(".transaction.highlight").removeClass('highlight');
    $(this).addClass('highlight');
    $(this).append("<input type='button' class='editButton' value='edit' />")
}

$("body").on('click', '.transaction', addEditButton());

I am getting an error message of "Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined" when using the above code.

I've tried searching through some of the same questions that have been posted about this and I now assume the error is because of the way I am using "this" but I am not sure how to fix the problem.

The code works just fine if I put all the code inside the $("body").on call, but not when I use the external addEditButton() function. Can anyone help please?

Upvotes: 3

Views: 14825

Answers (2)

caisah
caisah

Reputation: 2087

Don't call the function when you bind it, just pass it as reference.

$("body").on('click', '.transaction', addEditButton);

Upvotes: 7

Patrick Hund
Patrick Hund

Reputation: 20236

You're assigning the result returned by your addEditButton function, instead of a reference to the function itself. Drop the parentheses and it should work:

$("body").on('click', '.transaction', addEditButton);

Upvotes: 3

Related Questions