📅  最后修改于: 2023-12-03 15:31:36.624000             🧑  作者: Mango
Javascript provides us with several methods to manipulate the DOM (Document Object Model) dynamically. One such method is appendChild()
which is used to add a new child node to an existing parent node in the DOM.
However, by default, the appendChild()
method adds the new child node as the last child of the parent node. But what if we want to add the new child node at a specific index in the parent node? In this case, we can make use of some careful planning and a combination of other DOM manipulation methods to achieve this.
Let's say that we have an HTML unordered list (<ul>
element) with several list items (<li>
elements) and we want to add a new list item at a specific index in the list. For example, let's say we want to add a new item at index 2.
<ul id="myList">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ul>
First, we need to create a new list item (<li>
element) that we want to add at the desired index. We can use the createElement()
method to do this.
let newItem = document.createElement('li');
Next, we need to retrieve the parent node (<ul>
element) that we want to add the new item to. We can use the getElementById()
method or any other appropriate method for this.
let myList = document.getElementById('myList');
Now, we need to get a reference to the existing list item at the desired index (in our case, index 2) that we want to insert the new item before. We can use the childNodes
property to do this. This property returns an array-like object of all child nodes of the parent node.
let refNode = myList.childNodes[2];
Note that the childNodes
property returns all child nodes of the parent node, including text nodes, which may not be desirable in some cases. If we only want to retrieve element nodes, we can use the children
property instead.
let refNode = myList.children[2];
Next, we can make use of the insertBefore()
method to insert the new item before the reference node.
myList.insertBefore(newItem, refNode);
The first argument of insertBefore()
is the node to be inserted, and the second argument is the reference node that the new node should be inserted before.
This will add the new item at the desired index in the list.
<ul id="myList">
<li>item 1</li>
<li>item 2</li>
<li>new item</li>
<li>item 3</li>
<li>item 4</li>
</ul>
Adding a new child node at a specific index in the DOM can be achieved by using a combination of DOM manipulation methods as shown above. By careful planning and using the appropriate methods, we can achieve the desired result.