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

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

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

HTML


                        
    
提交评论

  • 2020-11-28 06:59
    $("div").addClass($('#foo').attr('class'));
    
    0 讨论(0)
  • 2020-11-28 07:00

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

    We could also try extending the jQuery prototype ($.fn) object to provide a new method that can be chained to the jQuery() function.

    Here's an extension of @pimvdb's solution to provide a function that copies all attributes

    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/

    Hope this helps.

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

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

    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.

    0 讨论(0)
  • 提交回复
    热议问题