2

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

Philippe Boissonneault
  • 3,949
  • 3
  • 26
  • 33
RussellHarrower
  • 6,470
  • 21
  • 102
  • 204

3 Answers3

5

The easiest method is to replace the h4 element completely:

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

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
3

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>.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • this copies the element, but wipes its attributes when im using it.. can't see why though?? – AGrush Sep 13 '19 at 09:53
1

A short vanilla-js solution

var newEl = document.createElement('h1');
newEl.innerHTML = oldEl.innerHTML;
oldEl.parentNode.replaceChild(newEl, oldEl);

Note this will destroy all event handlers and data added to oldEl or its descendants.

For a more complete solution, see NiettheDarkAbsol's answer.

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513