写一个关于DOM模型的简单程序
时间: 2024-03-07 07:49:28 浏览: 116
好的,我可以为您写一个简单的程序来演示DOM模型的基本操作。这个程序将创建一个新的HTML文档,向其中添加一些元素,并且修改这些元素的属性和样式。
首先,我们创建一个HTML文档,并向其中添加一个标题和一个段落元素:
```javascript
// 创建一个新的HTML文档
const doc = document.implementation.createHTMLDocument('My Document');
// 获取文档的 <head> 和 <body> 元素
const head = doc.getElementsByTagName('head')[0];
const body = doc.getElementsByTagName('body')[0];
// 添加标题和段落元素到 <body> 中
const titleElement = doc.createElement('title');
titleElement.innerText = 'My Document';
const pElement = doc.createElement('p');
pElement.innerText = '这是一个段落元素。';
body.appendChild(titleElement);
body.appendChild(pElement);
```
接着,我们可以修改段落元素的样式,将其背景色设置为红色,并将文本颜色设置为白色:
```javascript
// 修改段落元素的样式
pElement.style.backgroundColor = 'red';
pElement.style.color = 'white';
```
最后,我们可以修改段落元素的属性,将其添加一个自定义属性,并且输出段落元素的HTML代码:
```javascript
// 修改段落元素的属性
pElement.setAttribute('data-custom', '这是一个自定义属性。');
// 输出段落元素的HTML代码
console.log(body.innerHTML);
```
现在,我们可以运行这个程序,在控制台中查看输出结果。这个程序演示了如何使用DOM模型创建、修改和操作HTML元素,希望能够帮助您更好地理解DOM模型的基本操作。
阅读全文
相关推荐















