通过 DOM 将文本添加到 JavaScript 中的现有文本元素 [英] Adding text to an existing text element in JavaScript via DOM

查看:25
本文介绍了通过 DOM 将文本添加到 JavaScript 中的现有文本元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何将文本添加到已经有文本节点的 p 标签或 h1 标签.

I am trying to figure how to add text to a p tag or h1 tag that already has a text node.

例如:

var t = document.getElementById("p").textContent;
var y = document.createTextNode("This just got added");

t.appendChild(y);

<p id="p">This is some text</p>

这段代码给出了一个错误 appendChild is not a function.大多数帮助页面首先创建一个 p 标记,然后附加文本.

This code gives an error appendChild is not a function. Most of the help pages first create a p tag and then append the text.

向现有文本元素添加文本的正确方法是什么?

What is the right way to add text to an existing text element?

PS:我之前使用过 innerHTML 来做这件事,但为了学习目的,我想在这里避免它.

PS: I've used innerHTML before to do this, but for learning purposes I want to avoid it here.

推荐答案

appendChild 不是函数的原因是因为你是在 textContent你的 p 元素.

The reason that appendChild is not a function is because you're executing it on the textContent of your p element.

您只需选择段落本身,然后将您的新文本节点附加到该段落:

You instead just need to select the paragraph itself, and then append your new text node to that:

var paragraph = document.getElementById("p");
var text = document.createTextNode("This just got added");

paragraph.appendChild(text);

<p id="p">This is some text</p>

但是,如果您愿意,您可以只修改文本本身(而不是添加新节点):

However instead, if you like, you can just modify the text itself (rather than adding a new node):

var paragraph = document.getElementById("p");

paragraph.textContent += "This just got added";

<p id="p">This is some text</p>

这篇关于通过 DOM 将文本添加到 JavaScript 中的现有文本元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆