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
            Asked
            
        
        
            Active
            
        
            Viewed 1,758 times
        
    2
            
            
        
        Philippe Boissonneault
        
- 3,949
 - 3
 - 26
 - 33
 
        RussellHarrower
        
- 6,470
 - 21
 - 102
 - 204
 
- 
                    1`in this code` what code. Show us this code. – Code Whisperer Dec 10 '14 at 15:14
 - 
                    You could use this solution found in another question: http://stackoverflow.com/a/918803/2229572 – Caleb Lewis Dec 10 '14 at 15:15
 
3 Answers
5
            The easiest method is to replace the h4 element completely:
$('h4').replaceWith(function() {
    return $('<h1 />', { html: $(this).html() });
});
        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.