You should use the outerHtml
propery of the HTMLElement
you want to change.
In this way, it becomes very easy to change a span
to an a
nchor: we just need to replace ^<span
with <a
and </span>$
with </a>
.
Using a regular expression to change just the first and the last occurrence of the opening and closing tag, we keep the attributes as they originally were.
The code is here:
var newElement = $('a-selector').get(0).outerHTML.replace(/^<span/, "<a").replace(/<\/span>$/, "</a>");
$('a-selector').replaceWith(newElement);
This example uses jQuery. Please refer to this fiddle to see it working.