Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Failed to execute 'insertBefore' on 'Node': parameter 1 is not of type 'Node'

Tags:

javascript

Running into an error on this Dom manipulation

var prependData = $('#income_ranges').children().first().clone();
var prependedData = $('#income_ranges').children().last();
var list = document.getElementById("income_ranges");
list.insertBefore(prependData, prependedData);

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

I get an error when I run this code and I dont know why. Any help is appreciated.

like image 664
Kingsley Simon Avatar asked Jul 23 '15 14:07

Kingsley Simon


2 Answers

Can't test right now, but I am pretty sure that you get this error because you are switching between jQuery objects and vanilla JS objects. Use .get() on a jQuery object to get it's vanilla counterpart (see documentation).

So change the last line to:

list.insertBefore(prependData.get(0), prependedData.get(0));

Or go full jQuery (much prettier in my opinion):

var prependData = $('#income_ranges > :first-child').clone();
var prependedData = $('#income_ranges > :last-child');
prependData.insertBefore(prependedData);
like image 51
Anders Avatar answered Nov 18 '22 13:11

Anders


The elements you are adding to insertBefore() are jQuery objects and not native DOM objects, which is what it is expecting. You can overcome this by converting both prependData and prependedData to their native types.

var prependData = $('#income_ranges').children().first().clone()[0];
var prependedData = $('#income_ranges').children().last()[0];
var list = document.getElementById("income_ranges");
list.insertBefore(prependData, prependedData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="income_ranges">
    <span> Hello </span>
</div>

Reference

like image 36
Lyndsey Browning Avatar answered Nov 18 '22 13:11

Lyndsey Browning