Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Charlotte Junker
Charlotte Junker
10,261 Points

Failed to execute 'insertBefore' on 'Node'

Hi, I'm getting this error message and I cannot figure out why: Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.

I've checked for typos etc but maybe I am missing something obvious. Can anyone help?

HTML:

<div id='dashboard'>
    <div class='container' id='dash-top'>
      <div id='tab'>
        <h3>Dashboard</h3>
      </div>
      <div id='search'>
        <input type='text' placeholder='search'>
      </div>
    </div>
    <canvas id='widgets'></canvas>
  </div>

JS:

//insert alert into html...
function alertBox() {
  const widgets = document.getElementById('widgets');
  const parentDiv = widgets.parentNode;

// test correct div is logging out to console
  console.log(parentDiv);

  const alertDiv = document.createElement('div');
  const alertText = document.createElement('p');
  const closeAlert = document.createElement('p');
  alertText.innerHTML = '<span>Alert</span> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis in orci id ex interdum accumsan eget eu elit. In risus neque, fermentum sed nibh.';
  closeAlert.innerHTML = 'X';
  closeAlert.id = 'close-alert';
  alertDiv.id = 'alert';
  alertDiv.appendChild(alertText);
  alertDiv.appendChild(closeAlert);
  parentDiv.insertBefore(widgets, alertDiv);
}


//...when page loads
document.onload = alertBox();

2 Answers

Steven Parker
Steven Parker
231,248 Points

According to the MDN Documentation, the first argument to "insertBefore" is the node to be added, and the second one is the existing reference node.

But the arguments here are in the reverse order, which causes the error.

Charlotte Junker
Charlotte Junker
10,261 Points

Face palm! I do not know how I managed that - thank you so much!