更改标记名称但保留所有属性

Gil*_*e59 5 jquery

我有这样的事情:

<span id="anId" someOtherAttributes....>test</span>
Run Code Online (Sandbox Code Playgroud)

我想改成:

<a id="anId" theSameOtherAttributes...>test</a>
Run Code Online (Sandbox Code Playgroud)

我有两个问题:

  1. 如何更改标签名称?

    要么

  2. 如何复制所有属性?

Uku*_*kit 7

这是一个非优雅但有效的解决方案:

// 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); 
Run Code Online (Sandbox Code Playgroud)


Ben*_*Ben 0

我不打算对其进行编码,而是为了引导您朝正确的方向前进,查找如何在 jquery 中构建标签(类似于http://api.jquery.com/append/

然后使用诸如Iterating over element attribute with jQuery 之类的方法循环遍历每个标签,并将每个属性添加到附加标签中。

编辑:好的,这是一个示例:http ://jsfiddle.net/mazzzzz/xUUn3/