Can you set multiple attributes with the DOM's setAttribute function?

后端 未结 5 1178
暗喜
暗喜 2021-01-06 16:09

Let\'s say I wanted to create an input element using the DOM. Instead of doing something like this

var input = document.createElement(\"input\");
input.setAt         


        
相关标签:
5条回答
  • 2021-01-06 16:27

    Element.setAttribute sets a single attribute, but you could easily write a helper function:

    function setAttributes(elements, attributes) {
      Object.keys(attributes).forEach(function(name) {
        element.setAttribute(name, attributes[name]);
      })
    }
    

    Usage:

    var input = document.createElement("input");
    setAttributes(input, {
      class: "my-class",
      type: "checkbox",
      checked: "checked"
    })
    

    As other answers say, you could also use $.attr. That's great if your project already uses jQuery. If it doesn't, I'd use this function rather than adding a fairly heavyweight dependency for a simple task.

    0 讨论(0)
  • 2021-01-06 16:32

    In jQuery you can do:

    var $input = $("<input>", {class: "my-class", type: "checkbox", checked:"checked"});
    
    0 讨论(0)
  • 2021-01-06 16:39
    var opt = {"class":"my-class", "type": "checkbox", "checked":"checked"};
    
    Object.keys(opt).forEach( function(key){ input.setAttribute(key,opt[key]); } );
    
    0 讨论(0)
  • 2021-01-06 16:41

    Yes, You can do using Jquery.

    $(input).attr(
    {
      "data-test-1": num1, 
      "data-test-2": num2
    });
    
    0 讨论(0)
  • 2021-01-06 16:45

    I personally think you're taking DRY too far (the three statements do different things, so I don't see how it's not DRY.) But if you must abstract it, just write a function to do it:

    var input = document.createElement("input");
    
    function setAttributes(el, options) {
       Object.keys(options).forEach(function(attr) {
         el.setAttribute(attr, options[attr]);
       })
    }
    
    setAttributes(input, {"class": "my-class", "type": "checkbox", "checked": "checked"});
    
    console.log(input);

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