admin管理员组

文章数量:1406937

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

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

Share Improve this question edited Dec 10, 2014 at 15:18 Philippe Boissonneault 3,9493 gold badges27 silver badges33 bronze badges asked Dec 10, 2014 at 15:13 RussellHarrowerRussellHarrower 6,84025 gold badges113 silver badges225 bronze badges 2
  • 1 in this code what code. Show us this code. – Code Whisperer Commented Dec 10, 2014 at 15:14
  • You could use this solution found in another question: stackoverflow./a/918803/2229572 – Caleb Lewis Commented Dec 10, 2014 at 15:15
Add a ment  | 

3 Answers 3

Reset to default 5

The easiest method is to replace the h4 element pletely:

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

Example fiddle

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

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 plete solution, see NiettheDarkAbsol's answer.

本文标签: jqueryChange tagname with javascriptStack Overflow