javascript - Can you set multiple attributes with the DOM's setAttribute function? -
let's wanted create input element using dom. instead of doing this
var input = document.createelement("input"); input.setattribute("class", "my-class"); input.setattribute("type", "checkbox"); input.setattribute("checked", "checked");
is there dryer way write these 3 lines of code 1 line.
i know this
var attributes = ["class", "type", "checked"]; var values = ["my-class", "checkbox", "checked"]; (var = 0; < attributes.length; i++) { input.setattribute(attributes[i], values[i]) end
the problem is helpful if have boatload of attributes need add. if have 2 or three, less dry.
is there anyway can dry code?
yes can using jquery.
$(input).attr( { "data-test-1": num1, "data-test-2": num2 });
Comments
Post a Comment