最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use insertBefore() without second parameter? - Stack Overflow

programmeradmin0浏览0评论

In this example says that second parameter for insertBefore() method is optional:

The child node you want to insert the new node before. When not specified, the insertBefore method will insert the newnode at the end.

My code:

let li = document.createElement('LI');
li.appendChild(document.createTextNode("Water"));
let list = document.getElementById('list');
list.insertBefore(li);
<ul id="list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>

In this example says that second parameter for insertBefore() method is optional:

The child node you want to insert the new node before. When not specified, the insertBefore method will insert the newnode at the end.

My code:

let li = document.createElement('LI');
li.appendChild(document.createTextNode("Water"));
let list = document.getElementById('list');
list.insertBefore(li);
<ul id="list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>

But when I try to use insertBefore with one parameter I have an error:

Uncaught TypeError: Failed to execute 'insertBefore' on 'Node': 2 arguments required, but only 1 present.

But this code work correctly:

list.insertBefore(li, list.childNodes[0])
Share Improve this question asked May 9, 2018 at 9:42 Eugene ZalivadnyiEugene Zalivadnyi 4777 silver badges15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

In this example says that second parameter for insertBefore() method is optional:

It's incorrect, see MDN or the spec (though frankly that current spec is much harder to follow than the old one). (Unfortunately, accuracy and pleteness are ongoing issues with w3schools, strongly remend using MDN instead.) You can use null as the second argument, but you must provide it:

let li = document.createElement('LI');
li.appendChild(document.createTextNode("Water"));
let list = document.getElementById('list');
list.insertBefore(li, null);
<ul id="list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>

w3schools is wrong yet again. MDN is much more reliable:

insertBefore

referenceNode is not an optional parameter -- you must explicitly pass a Node or null. Failing to provide it or passing invalid values may behave differently in different browser versions.

发布评论

评论列表(0)

  1. 暂无评论