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
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.