How to resolve "Failed to convert JavaScript argument arg 0 [nsIDOMHTMLDivElement.appendChild]"

I have a json object returned from ajax, and when I warn it, it displays correctly, and I try to add them to an unordered list and add it to the place owner’s div, but it throws the above error.

function handleResponse() { if(httpa.readyState == 4){ var response = httpa.responseText; //alert(response); if(response!='empty') { //alert(response); eval("prod="+response); var len = prod.length; var st = "<ul>"; for(var cnt=0;cnt<len;cnt++) { st = st + "<li onclick='set("+prod[cnt].id+")'>"+prod[cnt].name+"</li>"; } st = st + "</ul>"; } var tt = document.getElementById('holder1'); tt.appendChild(st); // i even tried **tt.appendChild(eval(st));** tt.style.display = 'block'; } } 
+4
source share
2 answers

A few comments:

  • eval("prod="+response); - do not do this. It creates a global variable prod, can execute arbitrary code, does not allow the JS engine to speed up your code, and is usually considered bad coding practice.
    • Instead, use the JSON parser (either json.org or the helpers from your favorite library).
  • tt.appendChild(st); // i even tried **tt.appendChild(eval(st));** tt.appendChild(st); // i even tried **tt.appendChild(eval(st));** - appendChild takes a DOM node; st is a string, and eval(st) evaluates to st , assuming it contains JavaScript code (so running it in XML will result in a syntax error if you are not using E4X , which still has not created an object suitable for use with appendChild )
    • You must either parse the HTML code you created (via innerHTML , createDocumentFragment , or - again - using the helper from your favorite JS library)
  • Finally, if you do, consider using templates instead .
+3
source
 tt.innerHTML += st; 

As st is a string, not a DOM element.

+1
source

Source: https://habr.com/ru/post/1309080/


All Articles