This article describes the usage of insertBefore() when adding node function to js at a specified location. Share it for your reference. The specific analysis is as follows:
The function prototype is as follows:
insertBefore(parameter 1, parameter 2): Add node at the specified location
The specific code is as follows:
Copy the code as follows: <html>
<head>
<script type="text/javascript">
function t(){
var nodeli = document.createElement('li');//Create a li node
var li_text = document.createTextNode('blue sky');//Create a text node
nodeli.appendChild(li_text);//Add text node to li node
var nodeul = document.getElementsByTagName('ul')[0];//Get the first UL node
var nodeli1 = nodeul.getElementsByTagName('li')[2];//Get the third node under ul - autumn
nodeul.insertBefore(nodeli,nodeli1);//The function insertBefore() indicates which node is added before. The first parameter is the new node to be inserted, and the second parameter is the existing node
}
</script>
</head>
<body>
<div id="container">
<ul>
<li>Spring</li>
<li>Summer</li>
<li>Autumn</li>
<li>Winter</li>
</ul>
</div>
<hr />
<button onclick="t()" value="">Specify the location to add node</button>
</body>
</html>
I hope this article will be helpful to everyone's JavaScript programming.