Could not convert javascript argument arg 0 — Solution


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):

  1. use document.createElement() to create a DOM node:  
    var cart = document.createElement("ul");
  2. fill in that node with innerHTML (or jQuery’s .html()): cart.innnerHTML = "string";
  3. now you can use .appendChild() since the string in inside a DOM node: 
    document.body.appendChild(cart);

 
Solution 2 (better):

  1. create a text node out of the string:  
    var detailsNode = document.createTextNode(varContainingTheString);
  2. now use appendChild() and pass in the text node:  
    cartDiv.appendChild(detailsNode);
  3. and, finally, append that div to the body:
    document.body.appendChild(cartDiv);

Leave a Reply

Your email address will not be published. Required fields are marked *