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

后端 未结 11 1058
灰色年华
灰色年华 2020-11-28 06:50

How do I copy the attributes of one element to another element?

HTML


                        
    
提交评论

  • 2020-11-28 07:06

    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) })
    }
    
    0 讨论(0)
  • 2020-11-28 07:06

    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));
    });
    
    0 讨论(0)
  • 2020-11-28 07:08

    A non-jquery solution:

    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.

    0 讨论(0)
  • 2020-11-28 07:15

    You can use the native Node#attributes property: 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"));
    
    0 讨论(0)
  • 提交回复
    热议问题