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

In this example says that second parameter for insertBefore() method is optional:The child node you wan

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745516939a4631058.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信