This can be done using the replaceWith
function, here's an example:
$('h2').replaceWith(function() {
return $("<h1>" + $(this).html() + "</h1>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><h2>H2</h2><h2><span>H2spanola</span></h2>
*Notethatyouaretryingtoworkwithattributes(attr
)andboth<h1>
and<h2>
are tags tags used to define HTML headers.
Update : Based on
on this question from SOen , I discovered an interesting way to get the same result, the snippet follows:
$('h2').contents().unwrap().wrap('<h1/>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><h2>H2</h2><h2><span>H2spanola</span></h2>
Icomparedtheperformanceofthetwothrough jsperf and found that the first solution using the replaceWith
function is more efficient.
Follow the test link you made: JsPerf - Replace Tag .