I have the the following code
<b class="xyzxterms" style="cursor: default; ">bryant keil bio</b>
How would I replace the b
tag to a h1
tag but keep all other attributes and information?
To replace a DOM element with the specified HTML or DOM elements using jQuery, use the replaceWith() method. The replaceWith (content) method replaces all matched elements with the specified HTML or DOM elements. This returns the JQuery element that was just replaced, which has been removed from the DOM.
We can replace HTML elements using the jQuery . replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elements with the provided new content and return the set of elements that were removed.
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/
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].
@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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With