Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change tagname with javascript

Is there away to change <h4>text here</h4> to a <h1>text here</h1> I know how to add classes and change the style, but there is something in this code that has coded it to be a H4 when I want it to really be a H1

like image 599
RussellHarrower Avatar asked Jun 14 '26 11:06

RussellHarrower


2 Answers

The easiest method is to replace the h4 element completely:

$('h4').replaceWith(function() {
    return $('<h1 />', { html: $(this).html() });
});

Example fiddle

like image 177
Rory McCrossan Avatar answered Jun 16 '26 13:06

Rory McCrossan


A Vanilla JS solution:

function changeElementType(element, newtype) {
    var newelement = document.createElement(newtype);

    // move children
    while(element.firstChild) newelement.appendChild(element.firstChild);

    // copy attributes
    for( var i=0, a=element.attributes, l=a.length; i<l; i++) {
        newelement.attributes[a[i].name] = a[i].value;
    }

    // event handlers on children will be kept. Unfortunately, there is
    // no easy way to transfer event handlers on the element itself,
    // this would require a full management system for events, which is
    // beyond the scope of this answer. If you figure it out, do it here.

    element.parentNode.replaceChild(newelement, element);
}

You can now call, for instance:

changeElementType(document.getElementsByTagName('h4')[0], "h1");

to change the first <h4> on the page into an <h1>.

like image 36
Niet the Dark Absol Avatar answered Jun 16 '26 13:06

Niet the Dark Absol