ZBLOG

appendChild Node 节点如何打印文本值

如果你想打印一个通过 appendChild 方法添加到 DOM 的节点的文本值,你可以使用与前面相同的方法来访问该节点的 textContentnodeValue 属性。下面是一个示例,演示如何创建、附加和打印一个节点的文本值。

示例代码

<!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>

解释

  1. 创建文本节点

    const newTextNode = document.createTextNode("Hello, I'm a new node!");
    
  2. 获取父元素

    const parentNode = document.getElementById('parent');
    
  3. 将新节点附加到父元素

    parentNode.appendChild(newTextNode);
    
  4. 打印文本内容

    • 使用 textContent 属性打印整个父元素中包含的所有文本。

      console.log("Using textContent:", parentNode.textContent);
      
    • 使用 nodeValue 属性直接打印新创建的文本节点的值。

      console.log("New text node value using nodeValue:", newTextNode.nodeValue);
      

在这个例子中,我们通过 appendChild 添加了一个新的文本节点,并随后打印出它的内容。如果你只需要打印特定的新添加子节点,可以在添加之后直接引用该子节点并调用其属性。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=22987

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?