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

做~自己de王妃 提交于 2020-03-18 07:26:12

问题


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.setAttribute("class", "my-class");
input.setAttribute("type", "checkbox");
input.setAttribute("checked", "checked");

Is there a DRYer way to write these three lines of code into one line.

I know you could do something like this

var attributes = ["class", "type", "checked"];
var values = ["my-class", "checkbox", "checked"];

for (var i = 0; i < attributes.length; i++) {
  input.setAttribute(attributes[i], values[i])
end

The problem is that is only helpful if you have a boatload of attributes you need to add. If you only have two or three, this is even less DRY.

Is there anyway I can dry up this code?


回答1:


Yes, You can do using Jquery.

$(input).attr(
{
  "data-test-1": num1, 
  "data-test-2": num2
});



回答2:


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



回答3:


In jQuery you can do:

var $input = $("<input>", {class: "my-class", type: "checkbox", checked:"checked"});



回答4:


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.




回答5:


var opt = {"class":"my-class", "type": "checkbox", "checked":"checked"};

Object.keys(opt).forEach( function(key){ input.setAttribute(key,opt[key]); } );


来源:https://stackoverflow.com/questions/30535595/can-you-set-multiple-attributes-with-the-doms-setattribute-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!