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

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?

Answer

Yes, You can do using Jquery.

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

Leave a Reply

Your email address will not be published. Required fields are marked *