pimvdb
pimvdb

Reputation: 154828

NOT_FOUND_ERR when appending to table using jQuery

I did find several questions concerning the NOT_FOUND_ERR: DOM Exception 8 error in combination with jQuery, but they did not happen in a scenario like mine and as such they did not provide a solution.

Basically, I have an object and I'm iterating over it and then adding rows to a <table> with id="legend": http://jsfiddle.net/nt9gZ/.

var items  = [],
    obj    = {a: 1,
              b: 2};

$.each(obj, function(i, v) {
    items.push(
        $("<tr>").append(
            $("<td>").html(i),
            $("<td>").html(v)
        )
    );
});

// .empty() is to erase contents when running this piece of code again
$("#legend").empty().append(
                        $(items)
                     );

When I run this piece of code, I get the error:

Uncaught Error: NOT_FOUND_ERR: DOM Exception 8

on Chrome.

I'm not sure what exactly is wrong with my code.

Upvotes: 3

Views: 1639

Answers (5)

Amir Ismail
Amir Ismail

Reputation: 3883

Try this jsfiddle

you should loop over items in items array and append 'em one by one

Upvotes: 1

Igor Dymov
Igor Dymov

Reputation: 16460

I've update your code a bit: http://jsfiddle.net/nt9gZ/8/

Basically there problem with the array - append method does not take array of jQuery objects as an argument, only a sequence of elements. So I've used add method to collect all rows together.

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

You are trying to insert an array of arrays..

Add a .get(0) when you are pushing the created object in the array, so that you insert the actual DOM fragments..

$.each(obj, function(i, v) {
    items.push(
        $("<tr>").append(
            $("<td>").html(i),
            $("<td>").html(v)
        ).get(0)
    );
});

demo at http://jsfiddle.net/gaby/nt9gZ/7/

Upvotes: 4

grodzi
grodzi

Reputation: 5703

from your jsfiddle

Append do not expect array in the first argument. However, reading the doc, the second arg can be an array. I can't manage to pass an array and make it work (as the second argument) though.

Upvotes: 1

ashisrai_
ashisrai_

Reputation: 6568

I am not familiar with your below code

$("<tr>").append(
            $("<td>").html(i),
            $("<td>").html(v)
        )

But here is another way to achieve the same.

var items  = [],
obj = {a: 1, b: 2};

$.each(obj, function(i, v) {
    items.push("<tr>"+"<td>"+i+"</td><td>" + v +"</td></tr>");
});

$("#legend").append(items.join(""));

Upvotes: 1

Related Questions