更改标签名称,但保留所有属性 [英] Change the tag name but keep all the attributes

查看:90
本文介绍了更改标签名称,但保留所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的东西:

<span id="anId" someOtherAttributes....>test</span>

我要更改为:

<a id="anId" theSameOtherAttributes...>test</a>

我有两个问题:

  1. 如何仅更改标签名称?

  1. How can I change just the tag name?

如何复制所有属性?

推荐答案

这不是一个优雅但可行的解决方案:

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

这篇关于更改标签名称,但保留所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆