Как изменить тип элемента с помощью jquery
У меня есть следующий код
<b class="xyzxterms" style="cursor: default; ">bryant keil bio</b>
Как заменить тег b
тегом h1
, но сохранить все остальные атрибуты и информацию?
Ответы
Ответ 1
Здесь один из способов сделать это с помощью 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
Не уверен в 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
Не уверен, что это совместимо с кросс-браузером.
Возможна вариация:
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].
Ответ 3
@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);
};
Ответ 4
@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.)
Ответ 5
Единственный способ, о котором я могу думать, - это скопировать все вручную: пример 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);
});
Ответ 6
@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');
Ответ 7
Мне нравится идея @AndrewWhitaker и других, использовать плагин jQuery - добавить метод changeElementType()
. Но плагин похож на черный ящик, без матраса на код, если он litle и отлично работает... Итак, производительность необходима и важнее кода.
"Чистый javascript" имеет лучшую производительность, чем jQuery: я думаю, что код @FelixKling имеет лучшую производительность, чем @AndrewWhitaker и другие.
Здесь находится код "чистый Javavascript" (и "чистый DOM" ), заключенный в плагин jQuery:
(function($) { // @FelixKling 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);
Ответ 8
Вот метод, который я использую для замены тегов 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());
});
});
Ответ 9
С помощью jQuery
без перебора атрибутов:
Метод 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>
Ответ 10
Решение 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)
Ответ 11
Вот моя версия. Это в основном версия @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;
};