简体   繁体   中英

Wrap text content of a tag into another tag in javascript

I have the following html structure:

<span>foobar</span>

I would like to wrap the text content of this span into another tag like this using pure 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()

 // 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. 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/

You can archive this very easy by using the Javascript function innerHTML . Like that:

Note You really sure that you want wrap p tags inside a span tag?

 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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