-3

I used insertAfter (as per How to do insert After() in JavaScript without using a library?), however, in my case, it doesn't work.

Why?

<!doctype html>
<html lang="en">
    <head></head>
    <body>
        <table id="myTable">
            <tbody>
                <tr>
                    <td></td>
                    <td></td>
                </tr>
                <tr>
                    <td></td>
                    <td></td>
                </tr>
            </tbody>
        </table>
        <script>
            function insertAfter(newNode, referenceNode) {
                referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
            }

            _table = document.getElementById("myTable");
            _tbody = _table.getElementsByTagName("tbody")[0];
            n = _tbody.getElementsByTagName("TR").length;
            _referenceNode = _tbody.getElementsByTagName("TR")[n - 1]

            _newTR = "<tr><td>A very complex table<td></td><td>much more complex than in this example</td></tr>";

            parser = new DOMParser()
            _newNode = parser.parseFromString(_newTR, "text/xml");

            insertAfter(_newNode, _referenceNode);
        </script>
    </body>
</html>
Community
  • 1
  • 1
user310291
  • 36,946
  • 82
  • 271
  • 487
  • 3
    [You literally just asked this exact question](http://stackoverflow.com/questions/35758680/how-to-fix-this-javascript-error-when-creating-a-complex-table-dynamically). Do you want to be question banned? Because deleting and reasking questions is how you get question banned. – Sterling Archer Mar 02 '16 at 21:57
  • 1
    You can only use appendChild. Why do you doing all this things? – Citrullin Mar 02 '16 at 21:58

1 Answers1

1

_newNode is an XML document. You can't directly insert a #document into your HTML like that. (Otherwise you get this error: Uncaught HierarchyRequestError: Failed to execute 'insertBefore' on 'Node': Nodes of type '#document' may not be inserted inside nodes of type 'TBODY'.)

Try using

insertAfter(_newNode.childNodes[0], _referenceNode);

because the first child of the XML document is the element you're after.

Also, your HTML was invalid. Use:

_newTR = "<tr><td>A very complex table</td><td>much more complex than in this example</td></tr>";

Not

_newTR = "<tr><td>A very complex table<td></td><td>much more complex than in this example</td></tr>";
Hatchet
  • 5,320
  • 1
  • 30
  • 42
  • Thanks this wasn't obvious to know the difference between XML document and node for newbie like me. – user310291 Mar 02 '16 at 22:09
  • @user310291 `console.log` is your friend. – Hatchet Mar 02 '16 at 22:12
  • problem is that console.log is not very explicit enough for newbie like me. I have yet another problem http://stackoverflow.com/questions/35759582/how-to-use-javascript-domparser-parsefromstring-on-complex-string – user310291 Mar 02 '16 at 22:37