How to change an HTML tag using pure JavaScript

The other day I needed to easily change a heading from H2 to H4, while not having direct access to how it was being applied. Instead of attempting to modify the style for that specific element using a common CCS variable, or some similar method — I decided to actually change the tag with JavaScript so the default styles would automatically apply. Doing this is pretty simple but may not be correct practice, I’m not really sure what is in instances like this besides modifying the source from the back end. But this just seemed like the easiest method to take at the time.

Defining the RegEx

Before going to the code, I wanted to define the regex separately. Not many people are fluent in regular expression. I certainly am not one of those people. But the gist of this particular sequence is to only select the tag name, so that we can replace it.


And if you would like an explanation to any of the parts, look at this example.

The JavaScript

Finally, defining the JavaScript. First, if you would like to select the specific element to be changed, use the outerHTML attribute.

elementToReplace.outerHTML.replace(/(?<=<(?:\/)?)span(?:.*?)(?<!>)/gi, 'label')

Or when replacing all elements using a specific CSS selector.

document.querySelectorAll('.label').forEach(e => e.outerHTML = e.outerHTML.replace(/(?<=<(?:\/)?)span(?:.*?)(?<!>)/gi, 'label'));





Leave a Reply

Your email address will not be published. Required fields are marked *