Javascript 如何使用 jquery 更改元素类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8584098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:35:10  来源:igfitidea点击:

how to change an element type using jquery

javascriptjquery

提问by bammab

I have the the following code

我有以下代码

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

How would I replace the btag to a h1tag but keep all other attributes and information?

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

回答by Andrew Whitaker

Here's one way you could do it with jQuery:

这是您可以使用 jQuery 实现的一种方法:

var attrs = { };

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


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

Example:http://jsfiddle.net/yapHk/

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

Update, here's a plugin:

更新,这是一个插件:

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

Example:http://jsfiddle.net/mmNNJ/

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

回答by Felix Kling

Not sure about jQuery. With plain JavaScript you could do:

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

DEMO

演示

Not sure how cross-browser compatible this is though.

不确定这是如何跨浏览器兼容的。

A variation could be:

一个变化可能是:

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

For more information see Node.attributes[MDN].

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

回答by Jazzbo

@jakov and @Andrew Whitaker

@jakov 和 @Andrew Whitaker

Here is a further improvement so it can handle multiple elements at once.

这是进一步的改进,因此它可以一次处理多个元素。

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

回答by fiskhandlarn

@Jazzbo's answer returned a jQuery object containing an array of jQuery objects, which wasn't chainable. I've changed it so that it returns an object more similar to what $.each would have returned:

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

(Also did some code cleanup so it passes jslint.)

(还做了一些代码清理,以便通过 jslint。)

回答by Akash

With jQuerywithoutiterating over attributes:

随着jQuery遍历属性:

The replaceElemmethod below accepts old Tag, new Tagand contextand executes the replacement successfully:

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>

Good Luck...

祝你好运...

回答by kasdega

Only way I can think of is to copy everything over manually: example jsfiddle

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

HTML

HTML

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

Jquery/Javascript

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

回答by jakov

@Andrew Whitaker: I propose this change:

@Andrew Whitaker:我提出这个改变:

$.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;
};

Then you can do things like: $('<div>blah</div>').changeElementType('pre').addClass('myclass');

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

回答by Peter Krauss

I like the idea of @AndrewWhitaker and others, to use a jQuery plugin -- to add the changeElementType()method. But a plugin is like a blackbox, no mater about the code, if it is litle and works fine... So, performance is required, and is most important than code.

我喜欢@AndrewWhitaker 和其他人的想法,使用 jQuery 插件——添加changeElementType()方法。但是插件就像一个黑匣子,不管代码,如果它很小并且工作正常......所以,性能是必需的,而且比代码更重要。

"Pure javascript" have better performancethan jQuery: I think that @FelixKling's code have better performance than @AndrewWhitaker's and others.

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



Here a "pure Javavascript" (and "pure DOM") code, encapsulated into a jQuery plugin:

这里是一个“纯 JavaScript”(和“纯 DOM”)代码,封装到一个 jQuery 插件中

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

回答by Seth McCauley

Here is a method I use to replace html tags in jquery:

这是我用来替换 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());
  });

});

回答by svnm

Javascript solution

Javascript解决方案

Copy the attributes of old element to the new element

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

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

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

Replace the old element with the new element

用新元素替换旧元素

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