Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

jquery - Change the tag name but keep all the attributes

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...