2

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 !

A.Vinuela
  • 258
  • 1
  • 2
  • 14

3 Answers3

2

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>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
-1

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/

Nique Joe
  • 492
  • 5
  • 18
-1

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>
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79