How can I set multiple attributes at once with JavaScript? Unfortunately, I'm not able to use a framework like jQuery on this project. Here is what I have now:
var elem = document.createElement("img"); elem.setAttribute("src", "http://example.com/something.jpeg"); elem.setAttribute("height", "100%"); elem.setAttribute("width", "100%");
To set multiple attributes for an element at once with JavaScript, we can call the element's setAttribute method. const setAttributes = (el, attrs) => { for (const [key, val] of Object.
The multiple attribute in HTML allows user to enter more than one value. It is a Boolean attribute and can be used on <input> as well as <select> element, To allow multiple file uploads in HTML forms, use the multiple attribute. The multiple attribute works with email and file input types.
Definition and Usage When present, it specifies that the user is allowed to enter more than one value in the <input> element. Note: The multiple attribute works with the following input types: email, and file. Tip: For <input type="file"> : To select multiple files, hold down the CTRL or SHIFT key while selecting.
The attr() method in jQuery is used to set or return the attributes and values of the selected elements. To set multiple attributes and values: $(selector). attr({attribute:value, attribute:value, ...})
You could make a helper function:
function setAttributes(el, attrs) { for(var key in attrs) { el.setAttribute(key, attrs[key]); } }
Call it like this:
setAttributes(elem, {"src": "http://example.com/something.jpeg", "height": "100%", ...});
You might be able to use Object.assign(...)
to apply your properties to the created element. Although some "properties (elem.height etc.) are read-only, i.e. accessors with only a getter (undefined setter)."
Keep in mind that height
and width
attributes are defined in pixels, not percents. You'll have to use CSS to make it fluid.
var elem = document.createElement('img') Object.assign(elem, { className: 'my-image-class', src: 'https://dummyimage.com/320x240/ccc/fff.jpg', height: 120, // pixels width: 160, // pixels onclick: function () { alert('Clicked!') } }) document.body.appendChild(elem) // One-liner: // document.body.appendChild(Object.assign(document.createElement(...), {...}))
.my-image-class { height: 100%; width: 100%; border: solid 5px transparent; box-sizing: border-box } .my-image-class:hover { cursor: pointer; border-color: red } body { margin:0 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With