如何使用jQuery更改元素类型


Answers:


137

这是使用jQuery的一种方法:

var attrs = { };

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


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

示例: 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);

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


2
@FelixKling:谢谢,children没有用,但是有用contents
安德鲁·惠特克

1
@安德鲁·惠特克哇!!!你很厉害!因此,请确保我使用b.class或b.xyzxterms(xyzxterms是类的名称)
bammab 2011年

5
@AndrewWhitaker:如果我没看错,在您的插件中,第一个匹配元素的属性将应用于所有匹配元素。不一定是我们想要的。当集合中没有匹配的元素时,也会引发错误。这是插件的修改后的版本,它为每个匹配的元素保留自己的属性,并且不会在空集上触发错误:gist.github.com/2934516
Etienne

2
这就像一个魅力!除了当选择器未能找到任何匹配元素时,它都会向控制台抛出错误消息,因为this [0]是未定义的,访问属性中断。添加条件可解决此问题:if(this.length!= 0){...
ciuncan 2013年

1
@ciuncan:感谢您的反馈!确实应该将其包装在一个.each块中,如下面的答案所示。
Andrew Whitaker

14

不确定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);

演示

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

一个变化可以是:

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

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


您的代码的性能优于“纯jQuery”(例如,安德鲁的代码),但是内部标记有一些问题,请参见本示例中的斜体以及您的代码参考示例
彼得·克劳斯

如果正确,则可以定义“理想的jquery插件”,并通过jquery-plugin-template调用函数。
彼得·克劳斯

固定。问题在于,在复制第一个孩子之后,它不再有下一个同胞,因此while(child = child.nextSibling)失败了。谢谢!
Felix Kling 2014年

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

3

@Jazzbo的答案返回了一个jQuery对象,其中包含一个jQuery对象数组,该数组不能链接。我已经对其进行了更改,使其返回的对象与$ .each将返回的对象更相似:

    $.fn.changeElementType = function (newType) {
        var newElements,
            attrs,
            newElement;

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

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

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

            $(this).replaceWith(newElement);

            if (!newElements) {
                newElements = newElement;
            } else {
                $.merge(newElements, newElement);
            }
        });

        return $(newElements);
    };

(还进行了一些代码清除,因此它通过了jslint。)


这似乎是最好的选择。我唯一不了解的是为什么您将attrs的var声明从this.each()中移出了。放在那里就可以很好地工作:jsfiddle.net/9c0k82sr/1
Jacob C.说莫妮卡(Monica)

由于jslint,我对vars进行了分组:“(还进行了一些代码清除,因此它可以通过jslint。)”。我认为,其背后的想法是使代码更快(不必在每个each循环内重新声明var )。
fiskhandlarn

2

我能想到的唯一方法是手动复制所有内容:jsfiddle示例

的HTML

<b class="xyzxterms" style="cursor: default; ">bryant keil bio</b>

jQuery / JavaScript

$(document).ready(function() {
    var me = $("b");
    var newMe = $("<h1>");
    for(var i=0; i<me[0].attributes.length; i++) {
        var myAttr = me[0].attributes[i].nodeName;
        var myAttrVal = me[0].attributes[i].nodeValue;
        newMe.attr(myAttr, myAttrVal);
    }
    newMe.html(me.html());
    me.replaceWith(newMe);
});

2

@安德鲁·惠特克:我建议进行此更改:

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

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

    var newelement = $("<" + newType + "/>", attrs).append($(this).contents());
    this.replaceWith(newelement);
    return newelement;
};

然后,您可以执行以下操作: $('<div>blah</div>').changeElementType('pre').addClass('myclass');


2

我喜欢@AndrewWhitaker和其他人的想法,使用jQuery插件-添加 changeElementType()方法。但是,插件就像一个黑盒子,对代码无所谓,如果它很小并且可以正常工作……那么,性能是必需的,并且比代码更重要。

“纯JavaScript” 比jQuery 具有更好的性能:我认为@FelixKling的代码比@AndrewWhitaker和其他代码的性能更好。


这里是封装在jQuery插件中的“纯Javavascript”(和“纯DOM”)代码

 (function($) {  // @FelixKling's code
    $.fn.changeElementType = function(newType) {
      for (var k=0;k<this.length; k++) {
       var e = this[k];
       var new_element = document.createElement(newType),
        old_attributes = e.attributes,
        new_attributes = new_element.attributes,
        child = e.firstChild;
       for(var i = 0, len = old_attributes.length; i < len; i++) {
        new_attributes.setNamedItem(old_attributes.item(i).cloneNode());
       }
       do {
        new_element.appendChild(e.firstChild);
       }
       while(e.firstChild);
       e.parentNode.replaceChild(new_element, e);
      }
      return this; // for chain... $(this)?  not working with multiple 
    }
 })(jQuery);

2

这是我用来替换jquery中html标记的方法:

// Iterate over each element and replace the tag while maintaining attributes
$('b.xyzxterms').each(function() {

  // Create a new element and assign it attributes from the current element
  var NewElement = $("<h1 />");
  $.each(this.attributes, function(i, attrib){
    $(NewElement).attr(attrib.name, attrib.value);
  });

  // Replace the current element with the new one and carry over the contents
  $(this).replaceWith(function () {
    return $(NewElement).append($(this).contents());
  });

});

2

jQuery 迭代属性的情况下:

以下replaceElem方法接受old Tagnew Tagcontext成功执行替换:


replaceElem('h2', 'h1', '#test');

function replaceElem(oldElem, newElem, ctx) {
  oldElems = $(oldElem, ctx);
  //
  $.each(oldElems, function(idx, el) {
    var outerHTML, newOuterHTML, regexOpeningTag, regexClosingTag, tagName;
    // create RegExp dynamically for opening and closing tags
    tagName = $(el).get(0).tagName;
    regexOpeningTag = new RegExp('^<' + tagName, 'i'); 
    regexClosingTag = new RegExp(tagName + '>$', 'i');
    // fetch the outer elem with vanilla JS,
    outerHTML = el.outerHTML;
    // start replacing opening tag
    newOuterHTML = outerHTML.replace(regexOpeningTag, '<' + newElem);
    // continue replacing closing tag
    newOuterHTML = newOuterHTML.replace(regexClosingTag, newElem + '>');
    // replace the old elem with the new elem-string
    $(el).replaceWith(newOuterHTML);
  });

}
h1 {
  color: white;
  background-color: blue;
  position: relative;
}

h1:before {
  content: 'this is h1';
  position: absolute;
  top: 0;
  left: 50%;
  font-size: 5px;
  background-color: black;
  color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="test">
  <h2>Foo</h2>
  <h2>Bar</h2>
</div>

祝好运...


1
我喜欢你的答案!为什么?因为所有其他答案都将无法尝试执行一些简单的操作,例如将锚转换为标签。也就是说,请考虑对您的答案进行以下修复/修订:A)。您的代码不适用于选择器。B)您的代码需要执行不区分大小写的正则表达式。也就是说,这是我建议的修复程序:regexOpeningTag = new RegExp('^ <'+ $(el).get(0).tagName,'i'); regexClosingTag = new RegExp($(el).get(0).tagName +'> $','i');
zax

像这样替换纯HTML也将使您失去附加到对象的所有事件侦听器。
何塞·亚涅斯

1

Javascript解决方案

将旧元素的属性复制到新元素

const $oldElem = document.querySelector('.old')
const $newElem = document.createElement('div')

Array.from($oldElem.attributes).map(a => {
  $newElem.setAttribute(a.name, a.value)
})

用新元素替换旧元素

$oldElem.parentNode.replaceChild($newElem, $oldElem)

map创建一个新的未使用数组,可以将其替换forEach
Orkhan Alikhanov

1

这是我的版本。它基本上是@fiskhandlarn的版本,但是它没有构造新的jQuery对象,而是仅用新创建的元素覆盖了旧元素,因此不需要合并。
演示:http : //jsfiddle.net/0qa7wL1b/

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

  this.each( function( index ){

    var atts = {};
    $.each( this.attributes, function(){
      atts[ this.name ] = this.value;
    });

    var $old = $(this);
    var $new = $('<'+ newType +'/>', atts ).append( $old.contents() );
    $old.replaceWith( $new );

    $this[ index ] = $new[0];
  });

  return this;
};
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.