通过DOM向javascript中的现有文本元素添加文本 [英] adding text to an existing text element in javascript via DOM

查看:248
本文介绍了通过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不是函数。大多数帮助页面都首先创建一个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 不是函数是因为您在 p textContent 上执行它c>元素。

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天全站免登陆