Как скопировать все атрибуты одного элемента и применить их к другому?
Как скопировать атрибуты одного элемента в другой элемент?
HTML
<select id="foo" class="bar baz" style="display:block" width="100" data-foo="bar">...</select>
<div>No attributes yet</div>
JavaScript
var $div = $('div');
var $select = $('select');
//now copy the attributes from $select to $div
Ответы
Ответ 1
Вы можете использовать собственное свойство Node#attributes
: http://jsfiddle.net/SDWHN/16/.
var $select = $("select");
var $div = $("div");
var attributes = $select.prop("attributes");
// loop through <select> attributes and apply them on <div>
$.each(attributes, function() {
$div.attr(this.name, this.value);
});
alert($div.data("foo"));
Ответ 2
Рабочее решение на jsfiddle
EDIT
Обновлен jsfiddler
Javascript
$(function(){
var destination = $('#adiv').eq(0);
var source = $('#bdiv')[0];
for (i = 0; i < source.attributes.length; i++)
{
var a = source.attributes[i];
destination.attr(a.name, a.value);
}
});
HTML
<div id="adiv" class="aclass">A class</div>
<div id="bdiv" class="bclass">B class</div>
Это копирование атрибутов #bdiv
в #adiv
.
Ответ 3
Довольно простой
function cloneAttributes(element, sourceNode) {
let attr;
let attributes = Array.prototype.slice.call(sourceNode.attributes);
while(attr = attributes.pop()) {
element.setAttribute(attr.nodeName, attr.nodeValue);
}
}
Ответ 4
Мы могли бы также попытаться расширить объект прототипа jQuery ($.fn
), чтобы предоставить новый метод, который может быть привязан к функции jQuery().
Здесь расширение решения @pimvdb для предоставления функции, которая копирует все атрибуты
Использование будет таким:
$(destinationElement).copyAllAttributes(sourceElement);
Функция расширения может быть определена следующим образом:
(function ($) {
// Define the function here
$.fn.copyAllAttributes = function(sourceElement) {
// 'that' contains a pointer to the destination element
var that = this;
// Place holder for all attributes
var allAttributes = ($(sourceElement) && $(sourceElement).length > 0) ?
$(sourceElement).prop("attributes") : null;
// Iterate through attributes and add
if (allAttributes && $(that) && $(that).length == 1) {
$.each(allAttributes, function() {
// Ensure that class names are not copied but rather added
if (this.name == "class") {
$(that).addClass(this.value);
} else {
that.attr(this.name, this.value);
}
});
}
return that;
};
})(jQuery);
Пример доступен в http://jsfiddle.net/roeburg/Z8x8x/
Надеюсь, что это поможет.
Ответ 5
Не-jquery-решение:
function copy(element){
var clone = document.createElement(element.nodeName);
for(key in element){
clone.setAttribute(key,element[key]);
}
return clone;
}
Он копирует методы и другие вещи, которые вам, вероятно, не нужны, но, надеюсь, вы не против. Этот код маленький и простой.
Ответ 6
Я столкнулся с той же проблемой, и после того, как вложил много времени и усилий, я создаю этотклон текстовой области в редактируемый div с тем же атрибутом
select.getAttributeNames().forEach(attrName => {
$(div).attr(attrName, inputData.getAttribute(attrName));
});
Ответ 7
Так как Firefox 22, Node.трибуты больше не поддерживаются (не реализованы другими браузерами и удалены из спецификации). Он поддерживается только элементом Element (Element.attributes).
Ответ 8
Вы можете попробовать следующее:
function copyAttributes(from, to)
{
$($(from)[0].attributes).
each(function(){$(to).attr(this.nodeName, this.nodeValue);});
return $(to);
};
Оператор return позволяет писать такие вещи, как:
copyAttributes(some_element, $('<div></div>')).append(...) ...
Надеюсь, что это поможет.
Ответ 9
Синтаксис ES6 на одном вкладыше:
function cloneAttributes(target, source) {
[...source.attributes].forEach( attr => { target.setAttribute(attr.nodeName ,attr.nodeValue) })
}
И, как отмечалось в первом комментарии, вы, вероятно, не захотите копировать атрибут исходного идентификатора... поэтому этот файл сохранит его как атрибут "data-id" в случае, если вам нужна ссылка.
function cloneAttributes(target, source) {
[...source.attributes].forEach( attr => { target.setAttribute(attr.nodeName === "id" ? 'data-id' : attr.nodeName ,attr.nodeValue) })
}
Ответ 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
$("div").addClass($('#foo').attr('class'));