I’m in no way a coder but I got an idea. I create websites with the tool webflow and when you set up a CMS collection with a rich-text-field the client can add headlines including h1, which I don’t want them to. My idea is that with javascript replace every h1 with h2 within a class (so the page title doesn’t get changed).
So far I manage to create this:
var e = document.getElementsByTagName('h1')[0];
var d = document.createElement('h2');
d.innerHTML = e.innerHTML;
e.parentNode.replaceChild(d, e);
<h1>Don't change this</h1>
<div class="the-class">
<h1>Replace this with h2</h1>
</div>
4
Answers
You can use
querySelector
and use a proper CSS selector to match only<h1>
elements inside.the-class
:This will replace all
h1
elements anywhere inside.the-class
[edit 2023/04/18] Here is a utility function to change the name of any tag, whilst maintaining the properties of the original. It replaces the tagname part of
outerHTML
.Note: the browser automagically replaces the end tag.
See also.
querySelectorAll to select the h1s inside of a class, createElement to make the new h2, and replaceWith to swap.