如何更改 DOM

介绍

理解 DOM 系列的前两部分中,我们学会了 如何访问 DOM 中的元素如何穿越 DOM)。

接下来的步骤是学习如何添加、更改、更换和删除节点,这是一个JavaScript程序的实用例子,你需要能够在DOM中创建、修改和删除元素。

在本教程中,我们将讨论如何创建新节点并将其插入DOM,更换现有节点,并删除节点。

创建新节点

在静态网站中,通过直接在.html 文件中写入 HTML 来添加元素,在动态 Web 应用中,元素和文本通常用 JavaScript 添加。

Property/MethodDescription
createElement()Create a new element node
createTextNode()Create a new text node
node.textContentGet or set the text content of an element node
node.innerHTMLGet or set the HTML content of an element

首先,让我们创建一个index.html文件,并将其保存到一个新的项目目录中。

 1[label index.html]
 2<!DOCTYPE html>
 3<html lang="en">
 4
 5  <head>
 6    <title>Learning the DOM</title>
 7  </head>
 8
 9  <body>
10    <h1>Document Object Model</h1>
11  </body>
12
13</html>

右击页面上的任何地方,选择检查,打开开发人员工具,然后导航到 控制台

我们将在文档对象上使用createElement()来创建一个新的p元素。

1const paragraph = document.createElement('p');

我们创建了一个新的p元素,我们可以在 _Console 中测试它。

1console.log(paragraph)
1[secondary_label Output]
2<p></p>

段落变量输出一个空的p元素,如果没有任何文本,这并不太有用。

1paragraph.textContent = "I'm a brand new paragraph.";
2console.log(paragraph)
1[secondary_label Output]
2<p>I'm a brand new paragraph.</p>

createElement()textContent的组合创建了一个完整的元素节点。

另一种设置元素内容的方法是使用innerHTML属性,允许您将HTML以及文本添加到元素中。

1paragraph.innerHTML = "I'm a paragraph with <strong>bold</strong> text.";

<$>[注] 注: 虽然这将起作用,并且是向元素添加内容的一种常见方法,但使用innerHTML方法可能存在与使用cross-site scripting(XSS)(https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations)相关的风险,因为内线JavaScript可以添加到元素中。

还可以使用createTextNode()方法创建文本节点。

1const text = document.createTextNode("I'm a new text node.");
2console.log(text)
1[secondary_label Output]
2"I'm a new text node."

使用这些方法,我们创建了新的元素和文本节点,但直到它们被插入到文档之前,它们在网站的前端是不可见的。

将节点插入DOM

为了看到我们在前端创建的新文本节点和元素,我们需要将它们插入到文档中。 方法appendChild()insertBefore()用于添加元素到母元素的开始、中间或结尾,而replaceChild()用于用新节点代替旧节点。

Property/MethodDescription
node.appendChild()Add a node as the last child of a parent element
node.insertBefore()Insert a node into the parent element before a specified sibling node
node.replaceChild()Replace an existing node with a new node

要练习这些方法,让我们在HTML中创建一个任务列表:

1[label todo.html]
2<ul>
3  <li>Buy groceries</li>
4  <li>Feed the cat</li>
5  <li>Do laundry</li>
6</ul>

当您在浏览器中加载您的页面时,它将看起来像这样:

DOM Screenshot 1

为了在任务列表的末尾添加一个新项目,我们必须先创建该项目并添加文本,就像我们在上面的创建新节点部分一样。

1// To-do list ul element
2const todoList = document.querySelector('ul');
3
4// Create new to-do
5const newTodo = document.createElement('li');
6newTodo.textContent = 'Do homework';

现在我们已经为我们的新任务提供了完整的元素,我们可以将其添加到列表的末尾,使用appendChild()

1// Add new todo to the end of the list
2todoList.appendChild(newTodo);

你可以看到新的li元素已附加到ul的末尾。

1[label todo.html]
2<ul>
3  <li>Buy groceries</li>
4  <li>Feed the cat</li>
5  <li>Do laundry</li>
6  <li>Do homework</li>
7</ul>

DOM Screenshot 2

也许我们有更高的优先级任务要做,我们想将其添加到列表的开始,我们将不得不创建另一个元素,因为‘createElement()’只创建一个元素,不能重复使用。

1// Create new to-do
2const anotherTodo = document.createElement('li');
3anotherTodo.textContent = 'Pay bills';

这个方法需要两个参数 - 第一是要添加的新子节点,第二是将立即跟随新节点的姐妹节点。

1parentNode.insertBefore(newNode, nextSibling);

对于我们的要做列表示例,我们将在列表中的第一个元素孩子之前添加新的其他Todo元素,该元素目前是购买食品列表元素。

1// Add new to-do to the beginning of the list
2todoList.insertBefore(anotherTodo, todoList.firstElementChild);
1[label todo.html]
2<ul>
3  <li>Pay bills</li>
4  <li>Buy groceries</li>
5  <li>Feed the cat</li>
6  <li>Do laundry</li>
7  <li>Do homework</li>
8</ul>

DOM Screenshot 3

新节点已在列表开始时被成功添加,现在我们知道如何将节点添加到母元素中。

我们将修改现有任务,以展示如何更换节点.创建新元素的第一步保持不变。

1const modifiedTodo = document.createElement('li');
2modifiedTodo.textContent = 'Feed the dog';

就像「insertBefore()」一样,「replaceChild()」需要两个参数 - 新的节点和要更换的节点,如下面的伪代码所示。

1parentNode.replaceChild(newNode, oldNode);

我们将用修改的任务代替列表中的第三个元素。

1// Replace existing to-do with modified to-do
2todoList.replaceChild(modifiedTodo, todoList.children[2]);
1[label todo.html]
2<ul>
3  <li>Pay bills</li>
4  <li>Buy groceries</li>
5  <li>Feed the dog</li>
6  <li>Do laundry</li>
7  <li>Do homework</li>
8</ul>

DOM Screenshot 4

使用appendChild(),insertBefore()replaceChild()的组合,您可以在 DOM 中的任何地方插入节点和元素。

从 DOM 删除节点

现在我们知道如何创建元素,将它们添加到DOM中,并修改现有元素。最后一步是学习如何从DOM中删除现有节点。

MethodDescription
node.removeChild()Remove child node
node.remove()Remove node

使用上面的任务示例,我们希望在完成任务后删除项目. 如果您完成了家庭作业,您可以删除做家庭作业项目,该项目是列表中的最后一个孩子,用removeChild()删除。

1todoList.removeChild(todoList.lastElementChild);
1[label todo.html]
2<ul>
3  <li>Pay bills</li>
4  <li>Buy groceries</li>
5  <li>Feed the dog</li>
6  <li>Do laundry</li>
7</ul>

DOM Screenshot 5

另一种方法可以是删除节点本身,使用直接在节点上的删除()方法。

1// Remove second element child from todoList
2todoList.children[1].remove();
1[label todo.html]
2<ul>
3  <li>Pay bills</li>
4  <li>Feed the dog</li>
5  <li>Do laundry</li>
6</ul>

DOM Screenshot 6

在‘removeChild()’和‘remove()’之间,你可以从DOM中删除任何节点.你可能看到的另一种方法来从DOM中删除子元素是将一个母元素的‘innerHTML’属性设置为空串(`"").这不是偏好的方法,因为它不那么明确,但你可能会在现有代码中看到它。

结论

在本教程中,我们学会了如何使用JavaScript创建新节点和元素并将它们插入DOM中,并更换和删除现有节点和元素。

理解 DOM 系列中,你知道如何访问 DOM 中的任何元素,穿过 DOM 中的任何节点,并修改 DOM 本身。

Published At
Categories with 技术
comments powered by Disqus