program story

한 요소의 모든 속성을 복사하여 다른 요소에 적용하는 방법은 무엇입니까?

inputbox 2020. 12. 8. 08:01
반응형

한 요소의 모든 속성을 복사하여 다른 요소에 적용하는 방법은 무엇입니까?


한 요소의 속성을 다른 요소로 어떻게 복사합니까?

HTML

<select id="foo" class="bar baz" style="display:block" width="100" data-foo="bar">...</select>

<div>No attributes yet</div>

자바 스크립트

var $div = $('div');
var $select = $('select');

//now copy the attributes from $select to $div

http://jsfiddle.net/SDWHN/16/ 기본 Node#attributes속성을 사용할 수 있습니다 .

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"));

jsfiddle의 작업 솔루션

편집하다

jsfiddler 업데이트

자바 스크립트

$(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.


아주 간단

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

$.fnjQuery () 함수에 연결할 수있는 새로운 메서드를 제공하기 위해 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/ 에서 사용할 수 있습니다.

도움이 되었기를 바랍니다.


비 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.


I'm facing same problem and after invested lots of time and effort i am creating thisclone textarea into editable div with same attribute

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

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).


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:

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

Hope this helps.


ES6 syntax one liner:

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.

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

Javascript solution

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)

$("div").addClass($('#foo').attr('class'));

참고URL : https://stackoverflow.com/questions/6753362/how-to-copy-all-the-attributes-of-one-element-and-apply-them-to-another

반응형