简体   繁体   English

如何插入标签<br>使用 JavaScript 插入另一个标签?

[英]How can I insert a tag <br> into another tag using JavaScript?

I want to put a <br> tag in the end of every <text></text> tag.我想在每个<text></text>标签的末尾放一个<br>标签。 I tried using我尝试使用

 var para = document.createElement("br"); var element = document.getElementsByTagName("text"); element.appendChild(para);

but i think i can't use the element.appendChild for more than 1 tag.但我认为我不能将element.appendChild用于超过 1 个标签。 Am I right?我对吗?

"...but i think i can't use the element.appendChild for more than 1 tag. Am I right?" “...但我想我不能将 element.appendChild 用于超过 1 个标签。我说得对吗?”

Right.对。 There are two parts to your question.你的问题有两个部分。

First, you need to loop over the collection returned from getElementsByTagName() .首先,您需要遍历从getElementsByTagName()返回的集合。 It does not have the same set of methods and properties that individual elements have.它没有与单个元素相同的一组方法和属性。

Second, to insert a br element into each text element, you need to create a new br element each time since a node can only be in one location in the tree at a time.其次,要在每个text元素中插入一个br元素,每次都需要创建一个新的br元素,因为一个节点一次只能位于树中的一个位置。

 var elements = document.getElementsByTagName("text"); // loop over collection for (var i = 0; i < elements.length; i++) { // append a newly created `br` for each `text` elements[i].appendChild(document.createElement("br")); }
 <text>foo</text> <text>bar</text>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM