how to change the heading level of an html element using javascript

1k views Asked by At

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.

3

There are 3 answers

1
CertainPerformance On

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>

0
Derek Wang On

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>

0
Prasath Mani On

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>