js 创建dom元素
时间: 2023-09-13 19:11:02 浏览: 57
要在JavaScript中创建DOM元素,可以使用以下方法:
1. 使用createElement方法创建元素节点:
```javascript
const element = document.createElement('div');
```
2. 使用createTextNode方法创建文本节点:
```javascript
const textNode = document.createTextNode('Hello, World!');
```
3. 使用appendChild方法将元素节点添加到父节点中:
```javascript
const parentElement = document.getElementById('parent');
parentElement.appendChild(element);
```
4. 使用setAttribute方法设置元素节点的属性:
```javascript
element.setAttribute('class', 'my-element');
```
完整的示例代码如下:
```javascript
// 创建元素节点
const element = document.createElement('div');
// 创建文本节点
const textNode = document.createTextNode('Hello, World!');
// 设置元素节点的属性
element.setAttribute('class', 'my-element');
// 将文本节点添加到元素节点中
element.appendChild(textNode);
// 将元素节点添加到父节点中
const parentElement = document.getElementById('parent');
parentElement.appendChild(element);
```
这样就可以使用JavaScript动态地创建和添加DOM元素了。记得替换代码中的'parent'为要添加元素的父节点的ID或选择器。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)