Reputation: 48495
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%");
Upvotes: 133
Views: 255014
Reputation: 87
you can simply add a method "setAttributes" (with "s" at the end) to "Element" prototype like this:
Element.prototype.setAttributes = function(obj){
for(var prop in obj) {
this.setAttribute(prop, obj[prop])
}
}
P.S: you can define it in one line:
Element.prototype.setAttributes = function(obj){ for(var prop in obj) this.setAttribute(prop, obj[prop]) }
and you can call it normally as you call the other methods. The attributes are given as an object:
elem.setAttributes({"src": "http://example.com/something.jpeg", "height": "100%", "width": "100%"})
you can add an "if" statement to throw an error if the given argument is not an object.
Upvotes: 5
Reputation: 50592
2023 Update
Don't use this as an extension to Element.prototype
. In 2012, it was debatable practice. In 2023, the debate is settled: it's not the way to go about things. Manipulating the prototype of library-external classes has risks that are difficult or impossible to mitigate; this is an ugly tool. I tried to note that, but was apparently not emphatic enough.
However, you can read the internal approach of the method and write it as a function, it would work the same. I might use something like this:
const setAttributes = (el, attrs) =>
Object.keys(attrs)
.filter(key => el[key] !== undefined)
.forEach(key =>
typeof attrs[key] === 'object'
? Object.keys(attrs[key])
.forEach(innerKey => el[key][innerKey] = attrs[key][innerKey])
: el[key] = attrs[key]
);
http://jsfiddle.net/uL8tm603/46/
Original 2012 answer follows
If you wanted a framework-esq syntax (Note: IE 8+ support only), you could extend the Element
prototype and add your own setAttributes
function:
Element.prototype.setAttributes = function (attrs) {
for (var idx in attrs) {
if ((idx === 'styles' || idx === 'style') && typeof attrs[idx] === 'object') {
for (var prop in attrs[idx]){this.style[prop] = attrs[idx][prop];}
} else if (idx === 'html') {
this.innerHTML = attrs[idx];
} else {
this.setAttribute(idx, attrs[idx]);
}
}
};
This lets you use syntax like this:
var d = document.createElement('div');
d.setAttributes({
'id':'my_div',
'class':'my_class',
'styles':{
'backgroundColor':'blue',
'color':'red'
},
'html':'lol'
});
Try it: http://jsfiddle.net/ywrXX/1/
If you don't like extending a host object (some are opposed) or need to support IE7-, just use it as a function
Note that setAttribute
will not work for style
in IE, or event handlers (you shouldn't anyway). The code above handles style
, but not events.
Documentation
setAttribute
on MDN - https://developer.mozilla.org/en-US/docs/DOM/element.setAttributeUpvotes: 17
Reputation: 11
The most simple way is:
Create an array with objects into him, like: array = [{obj1}, {obj2}, etc...]
next, you iterate on array to set the key's object like the
attribute and the value's object like the value of attribute:
example: let arr = [{'id': 'myId'}, {'class': 'myClassname'}]
/iterate on array/
function setAt(array){
for (attr of array){
myElement.setAttribute(attr, array[attr])
}
}
later, you call the function passing your array like args: setAt(arr)
Upvotes: 0
Reputation: 11
var elem = document.createElement("img");
function setAttributes(attributes) {
for (let key in attributes) {
elem.setAttribute(key, attributes[key]);
}
}
setAttributes({src: "http://example.com/something.jpeg",height: "100%",width: "100%",});
Upvotes: 1
Reputation: 277
THE EASIEST: ` var elem = document.createElement("img");
var attrs = { src: "http://example.com/something.jpeg", height: "100%", width: "100%" }
Object.assign(elem, attrs); `
Upvotes: -2
Reputation: 21
That's an easy way
let div = document.getElementsByTagName("div")[0];
let attr = ["class", "id", "title"];
let attrVlu = ["ahmed", "mohamed", "ashraf"];
for(let i = 0; i < 3; i++) {
div.setAttribute(attr[i], attrVlu[i]);
}
Upvotes: 2
Reputation: 17457
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 }
Upvotes: 60
Reputation: 137
let elem = document.createElement("img");
Object.entries({"src": "http://example.com/something.jpeg"),
"height": "100%",
"width": "100%"}).forEach(kv => elem.setAttribute(kv[0], kv[1]));
Upvotes: 1
Reputation: 2088
No function example:
let checkbox = document.createElement('input');
for (const [key, value] of Object.entries({
type: 'checkbox',
id: 'sys-surname',
class: 'switcher23',
value: 1,
name: 'surname'
})) {
checkbox.setAttribute(key, value);
}
Upvotes: 2
Reputation: 79
I guess it's best way to set attributes at once for any element in this class.
function SetAtt(elements, attributes) {
for (var element = 0; element < elements.length; element++) {
for (var attribute = 0; attribute < attributes.length; attribute += 2) {
elements[element].setAttribute(attributes[attribute], attributes[attribute + 1]);
}
}
}
var Class = document.getElementsByClassName("ClassName"); // class array list
var Data = ['att1', 'val1', 'att2', 'val2', 'att3', 'val3']; //attributes array list
SetAtt(Class, Data);
Upvotes: 1
Reputation:
use this function to create and set attributes at the same time
function createNode(node, attributes){
const el = document.createElement(node);
for(let key in attributes){
el.setAttribute(key, attributes[key]);
}
return el;
}
use it like so
const input = createNode('input', {
name: 'test',
type: 'text',
placeholder: 'Test'
});
document.body.appendChild(input);
Upvotes: 1
Reputation: 369
const setAttributes = (el, attrs) =>
Object.entries(attrs)
.forEach(args =>
el.setAttribute(...args))
Upvotes: 7
Reputation: 1038
You could code an ES5.1 helper function:
function setAttributes(el, attrs) {
Object.keys(attrs).forEach(key => el.setAttribute(key, attrs[key]));
}
Call it like this:
setAttributes(elem, { src: 'http://example.com/something.jpeg', height: '100%' });
Upvotes: 15
Reputation: 707218
You can create a function that takes a variable number of arguments:
function setAttributes(elem /* attribute, value pairs go here */) {
for (var i = 1; i < arguments.length; i+=2) {
elem.setAttribute(arguments[i], arguments[i+1]);
}
}
setAttributes(elem,
"src", "http://example.com/something.jpeg",
"height", "100%",
"width", "100%");
Or, you pass the attribute/value pairs in on an object:
function setAttributes(elem, obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
elem[prop] = obj[prop];
}
}
}
setAttributes(elem, {
src: "http://example.com/something.jpeg",
height: "100%",
width: "100%"
});
You could also make your own chainable object wrapper/method:
function $$(elem) {
return(new $$.init(elem));
}
$$.init = function(elem) {
if (typeof elem === "string") {
elem = document.getElementById(elem);
}
this.elem = elem;
}
$$.init.prototype = {
set: function(prop, value) {
this.elem[prop] = value;
return(this);
}
};
$$(elem).set("src", "http://example.com/something.jpeg").set("height", "100%").set("width", "100%");
Working example: http://jsfiddle.net/jfriend00/qncEz/
Upvotes: 11
Reputation: 91
Try this
function setAttribs(elm, ob) {
//var r = [];
//var i = 0;
for (var z in ob) {
if (ob.hasOwnProperty(z)) {
try {
elm[z] = ob[z];
}
catch (er) {
elm.setAttribute(z, ob[z]);
}
}
}
return elm;
}
DEMO: HERE
Upvotes: 4
Reputation: 122908
Or create a function that creates an element including attributes from parameters
function elemCreate(elType){
var element = document.createElement(elType);
if (arguments.length>1){
var props = [].slice.call(arguments,1), key = props.shift();
while (key){
element.setAttribute(key,props.shift());
key = props.shift();
}
}
return element;
}
// usage
var img = elemCreate('img',
'width','100',
'height','100',
'src','http://example.com/something.jpeg');
FYI: height/width='100%'
would not work using attributes. For a height/width of 100% you need the elements style.height/style.width
Upvotes: 4
Reputation: 26753
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%", ...});
Upvotes: 165