I have something like this:
<span id="anId" someOtherAttributes....>test</span>
which I want to change into:
<a id="anId" theSameOtherAttributes...>test</a>
I have two questions :
How can I change just the tag name?
or
How can I copy all the attributes?
Here's a non-elegant, but working solution:
// create a new <a> element
new_element = $("<a/>");
// iterate over every attribute of the #some_id span element
$.each($("#some_id").get(0).attributes, function(i, attrib) {
// set each attribute to the specific value
$(new_element).attr(attrib.name, attrib.value);
});
// carry over the html content
new_element.html($("#some_id").html());
// finally, swap the elements
$("#some_id").replaceWith(new_element);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With