0

Maybe this is a basic question, but I should stress I know very little about these things. Essentially, in my page I have something like:

<h2>Some text there</h2>
<h2>Other text there</h2>

And I would like to make it simply into:

Some text there
Other text here

I mean, essentially, I want to remove the H2 surrounding the text. It'd be super easy to just delete it, but unfortunately I only have indirect access to the code. Is there any way to remove this dynamically using Javascript?

  • 1
    Without further details: [How to replace DOM element in place using Javascript?](https://stackoverflow.com/questions/843680/how-to-replace-dom-element-in-place-using-javascript) (convert the text into a `TextNode`) – Andreas Sep 18 '21 at 16:24
  • Thank you for your help. @DanZuzevich, it may have been partially my fault - I forgot to mention, when I posted it initially, that I know close to nothing about these subjects. if, for you, this may be a very simple question, for me, trying to ask this, and understand the answers, would be like trying to make a child who just learned the alphabet read an epic poem... – FlyingDonkey Sep 18 '21 at 16:55

2 Answers2

1

You can loop through all h2 elements and replace each element with a text node of the element's textContent (with document.createTextNode):

document.querySelectorAll('h2').forEach(e => e.parentNode.replaceChild(document.createTextNode(e.textContent), e))
<h2>Some text there</h2>
<br/>
<h2>Other text there</h2>
Spectric
  • 30,714
  • 6
  • 20
  • 43
  • 2
    Only thing I could see going wrong is that their might be other h2 elements that should be preserved. Without knowing the HTML layout though, it's not really possible to write a more specific selector. Upvoted. – Dan Zuzevich Sep 18 '21 at 16:36
  • Thank you. That was exactly my problem with his answer, too - that would replace all the H2, not just a few ones. I eventually came across with a better solution for my case, based on an entry from another question, I'm going to post it in a few minutes - but thank you all! – FlyingDonkey Sep 18 '21 at 16:56
-1

Eventually, I found this solution, which was perfect for my case, but I'd also want to thank everyone who posted here!

document.addEventListener('DOMContentLoaded', e => {
    const h2s = document.querySelectorAll("h2")

    h2s[0].outerHTML = h2s[0].innerHTML
    h2s[1].outerHTML = h2s[1].innerHTML
})