10 ответов:
вот один из способов вы можете сделать это с помощью 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/
не уверен насчет 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].
@Яков и @Эндрю Уитакер
вот дальнейшее улучшение, так что он может обрабатывать несколько элементов сразу.
$.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); };
единственный способ, который я могу придумать, это скопировать все вручную:пример 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: я предлагаю это изменение:
$.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');
мне нравится идея @AndrewWhitaker и других, чтобы использовать плагин jQuery -- чтобы добавить
changeElementType()метод. Но плагин похож на черный ящик, независимо от кода, если он маленький и работает нормально... Таким образом, производительность требуется, и это наиболее важно, чем код."чистый javascript" есть улучшенная производительность чем jQuery: я думаю, что код @FelixKling имеет лучшую производительность, чем @AndrewWhitaker и другие.
здесь "чисто Javavascript" (и "чистый 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);
вот метод, который я использую для замены html-тегов в 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 вернул объект jQuery, содержащий массив объектов jQuery,который не был цепочкой. Я изменил его так, что он возвращает объект, более похожий на то, что $.каждый бы вернулся:
$.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.)
С
jQueryбез перебора атрибутов:The
replaceElemспособ можно нижеold Tag,new Tagиcontextи успешно выполняет замену:
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>Удачи...
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)
Comments