Strange error when appending elements in JavaScript

613 views Asked by At

I've been getting a problem when trying to append an element in JavaScript, the error I've been getting looks a bit like this:

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

I'm also using using a framework called Interact.js just so you know

here's the peice of code that the browser isn't happy about:

var tempText = [];
var classNum = event.relatedTarget.getElementsByClassName('text');
var newCont = document.createElement('div');
for(var i = 0; i < classNum.length; i++){
    tempText.push(event.relatedTarget.getElementsByClassName('text')[i].textContent);
}
for(var i = 0; i < tempText.length; i++){
    var pText = document.createElement('p').appendChild(tempText);
    newCont.appendChild(pText[i]);

}

var placement = document.getElementById('toolbar')[0];
placement.appendChild(newCont);
2

There are 2 answers

0
Praveen Kumar Purushothaman On BEST ANSWER

I just noticed a small mistake. The document.getElementById returns only a single object. So don't use the [0]:

var placement = document.getElementById('toolbar'); // There is no [0]. Remove it.
placement.appendChild(newCont);

But the whole thing is really easy to do using jQuery. Since you are fine with using a jQuery solution, read on. Please include the jQuery library by adding this piece:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

And the JavaScript would be:

var tempText = [];
var classNum = event.relatedTarget.getElementsByClassName('text');
var newCont = document.createElement('div');
for (var i = 0; i < classNum.length; i++) {
  tempText.push(event.relatedTarget.getElementsByClassName('text')[i].textContent);
}
for (var i = 0; i < tempText.length; i++) {
  // Change here:
  var pText = $("<p />", {html: tempText});
  $(newCont).append(pText);
}

var placement = $('#toolbar');
placement.append(newCont);

Since I am unaware of the HTML underlying, I just guessed it and converted a few to jQuery.

3
trincot On

As you tagged your question with jquery, you can condense your code to this:

var $newCont = $('<div>');
$('.text', event.relatedTarget).each(function() {
    $newCont.append($('<p>').append($(this).text())); 
})
$('#toolbar').append($newCont);

Or in a functional programming way:

$('#toolbar').append($('<div>').append(
    $('.text', event.relatedTarget).map(function() {
        return $('<p>').append($(this).text()); 
    }).get()
));