简体   繁体   English

javascript 将一个标签的文本内容包装到另一个标签中

[英]Wrap text content of a tag into another tag in javascript

I have the following html structure:我有以下 html 结构:

<span>foobar</span>

I would like to wrap the text content of this span into another tag like this using pure javascript:我想使用纯 javascript 将此跨度的文本内容包装到另一个标签中:

<span><p>foobar</p></span>

I already tried this but without success:我已经尝试过但没有成功:

span.appendChild(virtualDoc.createElement('p'));

Thanks for reading me !感谢您阅读我!

Use Element.childNodes and .append()使用Element.childNodes.append()

 // DOM utility functions: const el = (sel, par) => (par || document).querySelector(sel); const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop); // Task: Wrap and re-append: const elTarget = el("div"); // Demo only. Use a better, unique selector instead const elParagr = elNew("p"); // Create the Paragraph elParagr.append(...elTarget.childNodes); // Append childNodes to Paragraph elTarget.append(elParagr); // Insert all back into the target element
 div {border: 2px solid red;} p {border: 2px solid blue;}
 <,-- P inside SPAN is invalid HTML markup, use a DIV instead! --> <div>foobar <b>baz</b></div>

Hello you can easily do this by having a function who will save the previous content first before adding the P element.你好,你可以通过 function 轻松地做到这一点,他会在添加 P 元素之前先保存以前的内容。 Please check the code below:请检查以下代码:

<span id="span">foobar</span>
<input type="button" value="add element" onclick="addElem()">

function addElem(){

  content = document.getElementById("span").innerHTML;
    document.getElementById("span").innerHTML = "<p>"+ content +"</p>";

}

Fiddle: https://jsfiddle.net/p2czo5qe/小提琴: https://jsfiddle.net/p2czo5qe/

You can archive this very easy by using the Javascript function innerHTML .您可以使用 Javascript function innerHTML轻松存档。 Like that:像那样:

Note You really sure that you want wrap p tags inside a span tag?注意您真的确定要将 p 标签包装在 span 标签内吗?

 function addElem() { spans = document.querySelectorAll('div span'); container = document.querySelector('div'); nc = ''; spans.forEach(s => { c = s.innerHTML; nc = nc + `<p>${c}</p>`; }); container.innerHTML = '<span>' + nc + '</span>'; }
 span { color: red; } span p { color: green; }
 <div> <span>foobar</span> <span>baz</span> </div> <input type="button" value="add element" onclick="addElem()">

Output Structure Output结构

<span>
  <p>foobar</p>
  <p>baz</p>
</span>

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

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