在HTML元素之前或之后添加文本

Joh*_*ohn 29 html javascript

如果我有一个HTML元素,如<div>内部的一些文本或另一个元素,我可以在此div之前或之后添加一些没有html元素的文本数据,只是纯文本?

我只想使用纯Javascript.

就像是 :

<div id="parentDiv">
   my text must be added here
  <div id="childDiv"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

Arn*_*anc 47

是的,您可以使用创建文本节点 document.createTextNode('the text')

然后你可以像一个元素一样插入它,使用appendChild或insertBefore.

在#childDiv之前插入文本的示例:

var text = document.createTextNode('the text');
var child = document.getElementById('childDiv');
child.parentNode.insertBefore(text, child);
Run Code Online (Sandbox Code Playgroud)

  • 您还可以尝试"insertAdjacentText"或"insertAdjacentHTML"方法:https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML (9认同)

Šim*_*das 27

仅供记录:

div.insertAdjacentHTML( 'beforeBegin', yourText );
Run Code Online (Sandbox Code Playgroud)

div你的孩子在哪里-DIV.

现场演示: http ://jsfiddle.net/ZkzDk/


Jua*_*rco 10

如果您只需要文本,我发现它element.insertAdjacentText(position, text)对于许多场景都很灵活,并且还兼容 IE6 等旧版浏览器。其中position正是您想要文本的位置,text是文本节点或只是一个字符串。选项有:

  • 'beforebegin'在元素本身之前。
  • 'afterbegin'就在元素内部,在它的第一个子元素之前。
  • 'beforeend'就在元素内部,在其最后一个子元素之后。
  • 'afterend'在元素本身之后。

像这样:

let div = document.getElementById('parentDiv');
div.insertAdjacentText('afterbegin', 'My Plain Text..');
Run Code Online (Sandbox Code Playgroud)