I got this error when I was trying to fill in a DOM node called cartDiv that would eventually be appended to the body with .appendChild(). It was working fine until I replaced the argument in
cartDiv.appendChild(cartDetails);
with a different variable. It had been working fine when cartDetails was the argument.
Summary: .appendChild() only accepts a DOM node as an argument, not a string.
Problem: The new variable I was trying to use as the argument in .appendChild was a string. .appendChild() only takes other DOM nodes as arguments. cite.
Solution 1 (see Solution 2 for a better way):
- use document.createElement() to create a DOM node:
var cart = document.createElement("ul");
- fill in that node with innerHTML (or jQuery’s .html()):
cart.innnerHTML = "string";
- now you can use .appendChild() since the string in inside a DOM node:
document.body.appendChild(cart);
Solution 2 (better):
- create a text node out of the string:
var detailsNode = document.createTextNode(varContainingTheString);
- now use appendChild() and pass in the text node:
cartDiv.appendChild(detailsNode);
- and, finally, append that div to the body:
document.body.appendChild(cartDiv);