Uncaught TypeError: Failed to execute ‘appendChild’ on ‘Node’: parameter 1 is not of type ‘Node’.

In developing a Javascript function, I ran into the following error when I looked at my console:

Uncaught TypeError: Failed to execute ‘appendChild’ on ‘Node’: parameter 1 is not of type ‘Node’.

I’ll start off by showing you what I was doing to throw the error and what I did to fix it.

The Below Code Doesn’t Work

I could have sworn that I was using appendChild properly but, alas, I wasn’t. Instead of passing a node to appendChild, I was passing a string.

var link = '<a class="wplauncher-link"> Example Link </a>';
var body = document.getElementsByTagName('body')[0].appendChild(link);

The Below Code Works

Instead, I should have created the link element first, added HTML to it, and then run appendChild. This is illustrated in the code below, which WORKS:

var link = document.createElement('a');
link.className = 'wplauncher-link';
link.innerHTML = 'Example Link';
document.body.appendChild(link);

If you need to add a string of HTML that is more complex than a link, I suggest using the insertAdjacentHTML method. An example of this is visible below:

var link = '<a class="wplauncher-link"> Example Link </a>';
document.body.insertAdjacentHTML('beforeend',link);

Leave a Reply

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