0

If I have something like:

<h2> test text </h2>

How would I use JavaScript to make it so that the text is now within a paragraph tag:

<p> test text </p>

I was thinking I could do something like:

var text = ('h2').text();

('h2').replace('<p>' + text + '</p>');

But it did not quite work.

cela
  • 2,352
  • 3
  • 21
  • 43
  • Are you using jQuery? If so, you need `$` before the function calls... – CertainPerformance Oct 22 '20 at 04:14
  • [Duplicate](https://www.google.com/search?q=site%3Astackoverflow.com+js+replace+element+type) of [How to replace DOM element in place using Javascript?](https://stackoverflow.com/a/40444300/4642212). – Sebastian Simon Oct 22 '20 at 04:17

3 Answers3

2

In vanilla JS, select the element, create a <p> element, and use replaceWith to replace the <h2> with the new <p>:

const h2 = document.querySelector('h2');
const p = document.createElement('p');
p.textContent = h2.textContent;
h2.replaceWith(p);

console.log(document.body.children[0].outerHTML);
<h2> test text </h2>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Just a note for others finding this -- while it will work in this specific case, it will fail for more complex HTML. Any attributes on the

    will be lost, and using textContent instead of innerHTML means that any elements within the

    will be ignored, only the plain text content will be used.

    – JoLoCo Feb 01 '22 at 14:06
0

You can use outerHTML to replace the tag name.

// document.getElementById("93").outerHTML = document.getElementById("93").outerHTML.replace(/wns/g,"lmn")

const h2List = document.getElementsByTagName('h2');
for (let index = 0; index < h2List.length; index ++) {
  h2List[index].outerHTML = h2List[index].outerHTML.replace(/h2/g, 'p');
}
<h2> test text </h2>
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
0

Simply change the outerHTML of the h2 tag like this:

const el = document.querySelector('h2');
el.outerHTML = '<p>' + el.innerHTML + '</p>';
<h2>Test 01</h2>
cela
  • 2,352
  • 3
  • 21
  • 43
Prasath Mani
  • 477
  • 1
  • 9
  • 10