node.insertBefore(new old)
时间: 2023-07-07 07:05:48 浏览: 56
`node.insertBefore(newNode, oldNode)` 是一个 DOM API 的方法,它会将 `newNode` 插入到 `oldNode` 的前面,作为其兄弟节点。如果 `oldNode` 为 `null`,则 `newNode` 被插入到 `node` 的末尾。
具体来说,这个方法做了以下几个步骤:
1. 获取 `oldNode` 的父节点 `parentNode`,如果 `parentNode` 为 `null`,则退出方法。
2. 将 `newNode` 插入到 `oldNode` 前面,作为其兄弟节点。
3. 返回被插入的 `newNode`。
示例代码:
```js
const parent = document.getElementById('parent');
const oldNode = document.getElementById('old');
const newNode = document.createElement('div');
newNode.textContent = 'Hello World!';
parent.insertBefore(newNode, oldNode);
```
相关问题
document.body.insertBefore
document.body.insertBefore() 是 JavaScript 中的一个 DOM 操作方法,可以用来将一个元素插入到指定父元素的指定位置。它的语法为:
```
parentNode.insertBefore(newNode, referenceNode);
```
其中,parentNode 是父元素节点,newNode 是要插入的新节点,referenceNode 是在哪个节点之前插入新节点。
例如,如果我们有一个 div 元素和一个 p 元素:
```
<div id="parent">
<p>我是第一个子元素</p>
</div>
```
我们可以使用 insertBefore() 方法将一个新的 span 元素插入到 div 元素中的 p 元素之前,代码如下:
```
var parent = document.getElementById("parent");
var newElement = document.createElement("span");
var referenceNode = parent.getElementsByTagName("p")[0];
parent.insertBefore(newElement, referenceNode);
```
这样,页面上的 HTML 结构就变成了:
```
<div id="parent">
<span></span>
<p>我是第一个子元素</p>
</div>
```
tr.insertBefore什么意思
`tr.insertBefore()` 是 JavaScript 中 DOM 元素的方法,用于在 HTML 表格中插入新的行。它接受两个参数:
- `newRow`: 要插入的新行。
- `nextRow`: 在哪一行之前插入新行。
例如,下面的代码将在 id 为 "myTable" 的表格中,在第二行前插入一行新的行:
```javascript
var table = document.getElementById("myTable");
var newRow = table.insertRow(1); // 在第二行前插入新行
```
`insertBefore()` 方法还可以用于在 DOM 树中插入新元素,它接受的第二个参数是要在哪个节点之前插入新节点。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)