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

Doing an error while manipulating Dom

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 am getting an error when I run this code and I don’t know why. Any help is appreciated.

+3


source to share


2 answers


Impossible to test right now, but I am sure you will get this error because you are switching between jQuery objects and JS Vanilla objects. Use .get()

jQuery on object to get its vanilla counterpart (see documentation ).

So, change the last line to:

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

      



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

var prependData = $('#income_ranges > :first-child').clone();
var prependedData = $('#income_ranges > :last-child');
prependData.insertBefore(prependedData);

      

+2


source


The elements you add to insertBefore () are jQuery objects and are not native DOM objects, as expected. 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>
      

Run codeHide result


Link

+1


source







All Articles