Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the tag name but keep all the attributes

Tags:

jquery

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 :

  1. How can I change just the tag name?

    or

  2. How can I copy all the attributes?

like image 475
Gillespie59 Avatar asked Jun 26 '11 08:06

Gillespie59


2 Answers

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); 
like image 136
Uku Loskit Avatar answered Dec 03 '22 21:12

Uku Loskit


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

like image 32
Alessandro Vendruscolo Avatar answered Dec 03 '22 21:12

Alessandro Vendruscolo