如何使用jquery更改元素类型

bam*_*mab 102 javascript jquery

我有以下代码

<b class="xyzxterms" style="cursor: default; ">bryant keil bio</b>
Run Code Online (Sandbox Code Playgroud)

如何将b标签替换为标签,h1但保留所有其他属性和信息?

And*_*ker 135

这是使用jQuery执行此操作的一种方法:

var attrs = { };

$.each($("b")[0].attributes, function(idx, attr) {
    attrs[attr.nodeName] = attr.nodeValue;
});


$("b").replaceWith(function () {
    return $("<h1 />", attrs).append($(this).contents());
});
Run Code Online (Sandbox Code Playgroud)

示例: http ://jsfiddle.net/yapHk/

更新,这是一个插件:

(function($) {
    $.fn.changeElementType = function(newType) {
        var attrs = {};

        $.each(this[0].attributes, function(idx, attr) {
            attrs[attr.nodeName] = attr.nodeValue;
        });

        this.replaceWith(function() {
            return $("<" + newType + "/>", attrs).append($(this).contents());
        });
    };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

示例: http ://jsfiddle.net/mmNNJ/

  • @AndrewWhitaker:如果我没错,在你的插件中,第一个匹配元素的属性将应用于所有匹配元素.这不一定是我们想要的.当集合中没有匹配的元素时,也会引发错误.这是您的插件的修改版本,它为每个匹配的元素保留自己的属性,并且不会在空集上触发错误:https://gist.github.com/2934516 (5认同)
  • @FelixKling:谢谢,`children`没有用,但`contents`没有. (2认同)
  • 这就像一个魅力!除了当选择器找不到任何匹配元素时,它会向控制台抛出一条错误消息,因为未定义此[0]访问属性中断.添加条件修复它:if(this.length!= 0){... (2认同)

Fel*_*ing 13

关于jQuery不确定.使用纯JavaScript,您可以:

var new_element = document.createElement('h1'),
    old_attributes = element.attributes,
    new_attributes = new_element.attributes;

// copy attributes
for(var i = 0, len = old_attributes.length; i < len; i++) {
    new_attributes.setNamedItem(old_attributes.item(i).cloneNode());
}

// copy child nodes
do {
    new_element.appendChild(element.firstChild);
} 
while(element.firstChild);

// replace element
element.parentNode.replaceChild(new_element, element);
Run Code Online (Sandbox Code Playgroud)

DEMO

虽然不确定跨浏览器兼容性如何.

变化可能是:

for(var i = 0, len = old_attributes.length; i < len; i++) {
    new_element.setAttribute(old_attributes[i].name, old_attributes[i].value);
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅Node.attributes [MDN].


小智 9

@jakov和@Andrew Whitaker

这是一个进一步的改进,因此它可以同时处理多个元素.

$.fn.changeElementType = function(newType) {
    var newElements = [];

    $(this).each(function() {
        var attrs = {};

        $.each(this.attributes, function(idx, attr) {
            attrs[attr.nodeName] = attr.nodeValue;
        });

        var newElement = $("<" + newType + "/>", attrs).append($(this).contents());

        $(this).replaceWith(newElement);

        newElements.push(newElement);
    });

    return $(newElements);
};
Run Code Online (Sandbox Code Playgroud)