Javascript 如何复制一个元素的所有属性并将它们应用于另一个?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6753362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to copy all the attributes of one element and apply them to another?
提问by Andrew
How do I copy the attributes of one element to another element?
如何将一个元素的属性复制到另一个元素?
HTML
HTML
<select id="foo" class="bar baz" style="display:block" width="100" data-foo="bar">...</select>
<div>No attributes yet</div>
JavaScript
JavaScript
var $div = $('div');
var $select = $('select');
//now copy the attributes from $select to $div
回答by pimvdb
You can use the native Node#attributes
property: http://jsfiddle.net/SDWHN/16/.
您可以使用本机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"));
回答by Tocco
A working solution on jsfiddle
EDIT
编辑
Updated jsfiddler
更新了 jsfiddler
Javascript
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
HTML
<div id="adiv" class="aclass">A class</div>
<div id="bdiv" class="bclass">B class</div>
That's copying #bdiv
attributes to #adiv
.
这就是将#bdiv
属性复制到 #adiv
.
回答by Joel Cox
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);
}
}
回答by Yair Levy
ES6 syntax one liner:
ES6 语法一行:
function cloneAttributes(target, source) {
[...source.attributes].forEach( attr => { target.setAttribute(attr.nodeName ,attr.nodeValue) })
}
And as noted in the first comment - you would probably don't want to copy the source id attribute... so this one will save it as a 'data-id' attribute in case you need a reference.
正如第一条评论中所指出的那样-您可能不想复制源 id 属性……因此,如果您需要参考,此属性会将其保存为“data-id”属性。
function cloneAttributes(target, source) {
[...source.attributes].forEach( attr => { target.setAttribute(attr.nodeName === "id" ? 'data-id' : attr.nodeName ,attr.nodeValue) })
}
回答by Ro Hit
We could also try extending the jQuery prototype ($.fn
) object to provide a new method that can be chained to the jQuery() function.
我们还可以尝试扩展 jQuery 原型 ( $.fn
) 对象,以提供可以链接到 jQuery() 函数的新方法。
Here's an extension of @pimvdb's solution to provide a function that copies all attributes
这是@pimvdb 解决方案的扩展,提供了一个复制所有属性的函数
The usage would be like so:
用法如下:
$(destinationElement).copyAllAttributes(sourceElement);
The extension function can be defined like so:
扩展函数可以这样定义:
(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);
An Example is available at http://jsfiddle.net/roeburg/Z8x8x/
http://jsfiddle.net/roeburg/Z8x8x/提供了一个示例
Hope this helps.
希望这可以帮助。
回答by john ktejik
A non-jquery solution:
非jquery解决方案:
function copy(element){
var clone = document.createElement(element.nodeName);
for(key in element){
clone.setAttribute(key,element[key]);
}
return clone;
}
It copies methods and other stuff you probably don't need, but hopefully you don't mind. This code is small and simple.
它复制了您可能不需要的方法和其他东西,但希望您不介意。这段代码小而简单。
回答by shubham singh
I'm facing same problem and after invested lots of time and effort i am creating thisclone textarea into editable div with same attribute
我面临同样的问题,在投入了大量时间和精力之后,我正在将这个克隆 textarea创建为具有相同属性的可编辑 div
select.getAttributeNames().forEach(attrName => {
$(div).attr(attrName, inputData.getAttribute(attrName));
});
回答by svnm
Javascript solution
Javascript解决方案
Copy the attributes of old element to the new element
将旧元素的属性复制到新元素
const $oldElem = document.querySelector('.old')
const $newElem = document.createElement('div')
Array.from($oldElem.attributes).map(a => {
$newElem.setAttribute(a.name, a.value)
})
Replace the old element with the new element, if required
如果需要,用新元素替换旧元素
$oldElem.parentNode.replaceChild($newElem, $oldElem)
回答by Werner Donné
You can try this:
你可以试试这个:
function copyAttributes(from, to)
{
$($(from)[0].attributes).
each(function(){$(to).attr(this.nodeName, this.nodeValue);});
return $(to);
};
The return statement lets you write things like:
return 语句允许您编写如下内容:
copyAttributes(some_element, $('<div></div>')).append(...) ...
Hope this helps.
希望这可以帮助。
回答by Leandro Barbosa
Since Firefox 22, Node.attributes is no longer supported (not implemented by other browsers and removed from the spec). It is only supported on Element (Element.attributes).
从 Firefox 22 开始,不再支持 Node.attributes(其他浏览器未实现并从规范中删除)。它仅在 Element (Element.attributes) 上受支持。