如何使用 jquery 更改元素类型

我有以下代码

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

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

81116 次浏览

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

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].

Here's one way you could do it with 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/

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/

Only way I can think of is to copy everything over manually: example 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);
});

@Andrew Whitaker: I propose this change:

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

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

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.

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


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

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

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

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


});

@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:

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

With jQuery without iterating over attributes:

The replaceElem method below accepts old Tag, new Tag and context and executes the replacement successfully:


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...

Javascript solution

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)

Here is my version. It's basically @fiskhandlarn's version, but instead of constructing a new jQuery object, it simply overwrites the old elements with the newly created ones, so no merging is necessary.
Demo: 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;
};