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
2 Answers
Reset to default 3In 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.