如何复制一个元素的所有属性并将其应用于另一个元素

How to copy all the attributes of one element and apply them to another?

本文关键字:元素 属性 另一个 应用于 何复制 复制 一个      更新时间:2023-09-26

如何将一个元素的属性复制到另一个元素?

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

您可以使用本地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"));

ES6语法:

function cloneAttributes(target, source) {
  [...source.attributes].forEach( attr => { target.setAttribute(attr.nodeName ,attr.nodeValue) })
}

正如第一条注释所指出的,你可能不想复制source id属性…所以这个会保存为'data-id'属性,以防你需要引用。

function cloneAttributes(target, source) {
  [...source.attributes].forEach( attr => { target.setAttribute(attr.nodeName === "id" ? 'data-id' : attr.nodeName ,attr.nodeValue) })
}

Pretty Simple

function cloneAttributes(element, sourceNode) {
  let attr;
  let attributes = Array.prototype.slice.call(sourceNode.attributes);
  while(attr = attributes.pop()) {
    element.setAttribute(attr.nodeName, attr.nodeValue);
  }
}

jsfield的一个可行的解决方案

编辑

更新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

我们还可以尝试扩展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/

获得

你可以试试:

function copyAttributes(from, to)
{
  $($(from)[0].attributes).
    each(function(){$(to).attr(this.nodeName, this.nodeValue);});
  return $(to);
};

return语句允许您编写如下内容:

copyAttributes(some_element, $('<div></div>')).append(...) ...

一个非jquery的解决方案:

function copy(element){
    var clone = document.createElement(element.nodeName);
    for(key in element){
        clone.setAttribute(key,element[key]);
    }
    return clone;
}

它复制方法和其他你可能不需要的东西,但希望你不介意。这段代码既小又简单。

我面临着同样的问题,在投入了大量的时间和精力之后,我正在将thisclone textarea创建为具有相同属性的可编辑div

select.getAttributeNames().forEach(attrName => {
  $(div).attr(attrName, inputData.getAttribute(attrName));
});

一个非常直接的解决方案是这样的:

const _$ = domQuery => document.querySelector(domQuery)
let div1 = _$('#div-1')
let div2 = _$('#div-2')
for(attr of div1.attributes) {
  div2.setAttribute(attr.name, attr.value);
}
.my-div {
height: 100px;
width: 100px;
}
<h1>div-1</h1>
<div atribute-test="test" class="my-div" style="background: red" id="div-1"></div>
<h1>div-2</h1>
<div id="div-2"></div>

自Firefox 22以来,Node。属性不再被支持(其他浏览器没有实现,并从规范中删除)。它只支持Element (Element.attributes)

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)
$("div").addClass($('#foo').attr('class'));