JavaScript 中的节点
JavaScript 使约定能够跟踪 HTML 元素
父节点和子节点。通常,如果我们在另一个元素下有一个元素,则此模式的整体结构将称为父子树
。
在 JavaScript 中,我们可以更改父元素的任何子元素。此外,我们可以添加和删除孩子。
在这里,我们将看到两个示例,其中一个将解释我们如何区分多种类型的子元素。另一个示例将描述将新的子元素附加到父元素。
在 JavaScript 中从父节点中选择子节点
在这种情况下,我们将启动一个具有多个 p
元素和一个 article
元素的 div
元素。驱动是挑选所有 p
元素并以不同的色调为它们着色以区分 article
和 p
元素。
让我们关注代码行以便更好地理解。
代码片段:
<!DOCTYPE html>
<html>
<body>
<p>Hello World!</p>
<article>
Howdy!
</article>
<p>Click button to change the color of all p elements.</p>
<button onclick="changeColor()">Hit it</button>
<script>
function changeColor() {
const Nodelist = document.querySelectorAll("p");
for (let i = 0; i < Nodelist.length; i++) {
Nodelist[i].style.color = "blue";
}
}
</script>
</body>
</html>
输出:
在 JavaScript 中将新的子节点附加到特定的父节点
在这里,我们将看到一个实例,我们将在其中附加一个新的子节点。我们将有一个带有多个 p
元素的 div
元素。
将从脚本标签添加一个新节点。首先,我们将执行 createElement
并创建 p
标签。
稍后我们会将文本添加到 p
元素。下一步将把这个新节点附加到父节点,这个新节点将自动添加到 HTML 预览
。
代码片段:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="div1">
<p>paragraph 1.</p>
<p>paragraph 2.</p>
</div>
<script>
const p = document.createElement("p");
const node = document.createTextNode("paragraph 3.");
p.appendChild(node);
const element = document.getElementById("div1");
element.appendChild(p);
</script>
</body>
</html>
输出:
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。