0

I have a WordPress site that is using a theme to create some pages. Unfortunately, its creating an H1 in a location I cant edit (only the text, "Home" in this case) and I would like to add my own H1 in another text block location. I'd like to programmatically remove the first H1 and I can do this for H1s (sample page I built by changing it to "body") with this code. (I set i to 0 to only replace the first instance):

<script>
    const hTwos = document.querySelectorAll('h1');
    for (let i = 0; i < hTwos.length; i++) {
       hTwos[0].outerHTML = hTwos[i].outerHTML.replace(/h1/g,"body");
    };
</script>

However, when there is a class assigned to the H1 the code does not remove it? Is there a way to remove the HTML code for <h1 class="header-section__title">Home</h1> from the page using jscript?

Any help would be greatly appreciated.

cloned
  • 6,346
  • 4
  • 26
  • 38

2 Answers2

0

You can select the first one then use classList for remove class and textContent for change text like:

const firstH1 = document.querySelectorAll('h1')[0];
firstH1.classList.remove('header-section__title');
firstH1.textContent = 'My edited title';
<h1 class='header-section__title'>Test 1</h1>
<h1>Test 2</h1>
<h1>Test 3</h1>

Reference:

Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
  • Thanks guys, very imaginative and it seems to have the desired result on page. Now I can add my own H1. Just one related question. When I review the page using the chrome developer tools to search for the H1 or class, I still see multiple H1s in the page code, so the script is running after the page load and rewriting that one element? Is there a way to remove it so SEO doesnt "see" multiple H1s? Thanks! – Dave McVie Jan 25 '22 at 15:31
  • Seems like new question :) please acept the answer. – Simone Rossaini Jan 25 '22 at 18:43
0

You can use the remove method to remove an element from the DOM.

There's also no point using the querySelectorAll method and looping over the results if you're only going to act on the first result. Just use the querySelector method, which only returns the first result.

const h1 = document.querySelector('h1');
if (h1) { h1.remove(); }

NB: This will completely remove the element and its content from the DOM. If you just want to change it to a different tag, you would need to replace the element, as shown in this answer:

const h1 = document.querySelector('h1');
const newEl = document.createElement('div');
newEl.innerHTML = h1.innerHTML;
h1.parentNode.replaceChild(newEl, h1);
Richard Deeming
  • 29,830
  • 10
  • 79
  • 151