javascript 未捕获的类型错误:无法在“节点”上执行“插入前”:参数 1 的类型不是“节点”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31590625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Failed to execute 'insertBefore' on 'Node': parameter 1 is not of type 'Node'
提问by Kingsley Simon
Running into an error on this Dom manipulation
在此 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 get an error when I run this code and I dont know why. Any help is appreciated.
运行此代码时出现错误,我不知道为什么。任何帮助表示赞赏。
采纳答案by Anders
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).
现在无法测试,但我很确定您会收到此错误,因为您正在 jQuery 对象和 vanilla JS 对象之间切换。.get()
在 jQuery 对象上使用以获得它的 vanilla 对应物(请参阅文档)。
So change the last line to:
因此,将最后一行更改为:
list.insertBefore(prependData.get(0), prependedData.get(0));
Or go full jQuery (much prettier in my opinion):
或者使用完整的 jQuery(在我看来更漂亮):
var prependData = $('#income_ranges > :first-child').clone();
var prependedData = $('#income_ranges > :last-child');
prependData.insertBefore(prependedData);
回答by Lyndsey Browning
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.
您添加到 insertBefore() 的元素是 jQuery 对象,而不是本机 DOM 对象,这正是它所期望的。您可以通过将 prependData 和 prependedData 都转换为它们的本机类型来克服这个问题。
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>