如果你想打印一个通过 appendChild
方法添加到 DOM 的节点的文本值,你可以使用与前面相同的方法来访问该节点的 textContent
或 nodeValue
属性。下面是一个示例,演示如何创建、附加和打印一个节点的文本值。
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Append Child and Print Text Value</title>
</head>
<body>
<div id="parent"></div>
<script>
// 创建一个新的文本节点
const newTextNode = document.createTextNode("Hello, I'm a new node!");
// 获取父元素
const parentNode = document.getElementById('parent');
// 将新节点附加到父元素
parentNode.appendChild(newTextNode);
// 打印附加后节点的文本内容
console.log("Using textContent:", parentNode.textContent); // 打印整个父元素的文本内容
console.log("New text node value using nodeValue:", newTextNode.nodeValue); // 打印新文本节点的值
</script>
</body>
</html>
解释
创建文本节点:
const newTextNode = document.createTextNode("Hello, I'm a new node!");
获取父元素:
const parentNode = document.getElementById('parent');
将新节点附加到父元素:
parentNode.appendChild(newTextNode);
打印文本内容:
使用
textContent
属性打印整个父元素中包含的所有文本。console.log("Using textContent:", parentNode.textContent);
使用
nodeValue
属性直接打印新创建的文本节点的值。console.log("New text node value using nodeValue:", newTextNode.nodeValue);
在这个例子中,我们通过 appendChild
添加了一个新的文本节点,并随后打印出它的内容。如果你只需要打印特定的新添加子节点,可以在添加之后直接引用该子节点并调用其属性。
内容由零声教学AI助手提供,问题来源于学员提问