Setting multiple attributes for an element at once with JavaScript
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%", ...});
How to set multiple attributes on the same element
If you only use setAttribute
for styling, you could fix it like this:
function setAttribute(element, key, value) {
element.style[key] = value
}
setAttribute(document.body, "backgroundColor", "red")
Note that you need to use the javascript version of styling (backgroundColor instead of background-color).
Setting multiple attributes for an element
Use
'html'
in your comparison. Also passthis
context inrecursiveSet
function to referthis
todiv
element.this
always refers to the “owner” of the function we're executing. If there is no owner, it will refer to thewindow
..
Try this:
var manipulateAttributes = function(attr, element) { var recursiveSet = function(at, set) { for (var prop in at) { /* check if object and not a dom node or array */ if (typeof at[prop] == 'object' && at[prop].dataset == null && at[prop][0] == null) { recursiveSet(at[prop], set [prop]); } else if (prop == 'html') { this.innerHTML = at[prop]; } else { set [prop] = at[prop]; } } }.bind(element); recursiveSet(attr, element);}var test = document.getElementById("test");
manipulateAttributes({ html: 'hellop', style: { background: "lightGreen", color: "blue", width: "100px" }, className: "testclass", onclick: function(e) { alert("the test div has been clicked and its width is: " + this.style.width); }}, test);
.testclass { font-size: 32px; font-weight: bold; cursor: pointer;}
<div id="test" style="width:200px;height:200px;background:#000;color:#fff;">Test</div>
Set multiple attributes for an HTML element using jQuery?
$('img').attr({'src':'http://example.com/something.jpeg', 'height':'100%', 'width':'100%'});
$('img') <= coresponding HTML element which you want to set the attributes
.attr(
{
'htmlAttributeName': 'attributeValue',
'anotherHtmlAttributeName': 'attributeValue',
....
}
)
Can you set multiple attributes with the DOM's setAttribute function?
Yes, You can do using Jquery.
$(input).attr(
{
"data-test-1": num1,
"data-test-2": num2
});
Trying to set multiple Attributes at the same time
Kind of hard to understand what you're asking but.. it's something like the following snip? What I don't understand is why you're trying to create a new Element..
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]); } }};
Element.prototype.inputSet = function(ids, classs, types, placeholders){ // just like your "setAttributes" method... use the This to set the attributes return this.setAttributes({ 'id' : `${ids}`, 'class' : `${classs}`, 'type' : `${types}`, 'placeholder' : `${placeholders}` }); };document.querySelector('#sample').inputSet('abc', 'for');
.for { border:1px solid red; width:100px; height: 100px;}
<div id="sample"></div>
How do I add multiple atrributes to an element in JavaScript?
There isn't any javascript method to do it, but you can convert your string to array and call setAttribute
on the target element on every iterate of the array. like this:
let el = document.getElementById("targetId")
let attrs = ' min="0" step="5" max="100" '.trim().replace(/\"/g,"").split(" ")
attrs.forEach(attr => {
const [key,value] = attr.split('=');
el.setAttribute(key,value)
})
How to set multiple attributes with one value function?
UPDATE (July 8th 2016) This answer applies to d3 v3.x — NOT v4.x. For the latter version, see Tim Hayes's answer, also on this page. Or... just swap attr
with attrs
in my answer below, and don't forget to require/import/script-embed d3-selection-multi
. And... don't miss the bit about using .each
, which may be useful to you.
Yeah, it's possible by passing in a hash (like jQuery's css()
method):
d3.select('body').append('svg').selectAll('circle')
.data(data)
.enter().append('circle')
.attr({
cx: function (d) { return d.x; },
cy: function (d) { return d.y; },
r: function (d) { return d.r; }
});
This works for style()
as well.
If the reoccurring function (d) {}
start to feel like too much, this is another approach:
d3.select('body').append('svg').selectAll('circle')
.data(data)
.enter().append('circle')
.each(function (d) {
d3.select(this).attr({
cx: d.x,
cy: d.y,
r: d.r
});
})
NOTE: this feature only exists in d3.js v2.10.0 or higher
set multi attributes at once without jquery
Sure, you could use a loop.
function setAttributes(el, attrs) {
Object.keys(attrs).forEach(function (attr) {
el.setAttribute(attr, attrs[attr]);
});
}
var aTag = document.createElement('a');
setAttributes(aTag, {
href: oUrl,
rel: "test",
target: "_blank"
});
Group multiple attributes based on category JAVASCRIPT. Works for one but not all attributes
You could group by category and take out the values for adding to an array.
var json = '[{"category":"Messaging","data":[7433],"backgroundColor":"rgba(255, 99, 132, 0.2)","borderColor":"rgba(255,99,132,1)","borderWidth":2},{"category":"Price Promo","data":[774],"backgroundColor":"rgba(255, 159, 64, 0.2)","borderColor":"rgba(255, 159, 64, 1)","borderWidth":2},{"category":"Usability","data":[5993],"backgroundColor":"rgba(255, 159, 64, 0.2)","borderColor":"rgba(255, 159, 64, 1)","borderWidth":2},{"category":"Messaging","data":[7624],"backgroundColor":"rgba(255, 99, 132, 0.2)","borderColor":"rgba(255,99,132,1)","borderWidth":2},{"category":"Price Promo","data":[900],"backgroundColor":"rgba(255, 159, 64, 0.2)","borderColor":"rgba(255, 159, 64, 1)","borderWidth":2},{"category":"Usability","data":[5865],"backgroundColor":"rgba(255, 159, 64, 0.2)","borderColor":"rgba(255, 159, 64, 1)","borderWidth":2},{"category":"Messaging","data":[7161],"backgroundColor":"rgba(255, 99, 132, 0.2)","borderColor":"rgba(255,99,132,1)","borderWidth":2},{"category":"Price Promo","data":[1005],"backgroundColor":"rgba(255, 159, 64, 0.2)","borderColor":"rgba(255, 159, 64, 1)","borderWidth":2},{"category":"Usability","data":[5940],"backgroundColor":"rgba(255, 159, 64, 0.2)","borderColor":"rgba(255, 159, 64, 1)","borderWidth":2}]', result = Object.values(JSON .parse(json) .reduce((r, { category, borderWidth, ...o }) => { r[o.category] = r[o.category] || { category, data: [], backgroundColor: [], borderColor: [], borderWidth }; Object.entries(o).forEach(([k, v]) => r[o.category][k] = (r[o.category][k] || []).concat(v)); return r; }, {}));
console.log(result);
Related Topics
Add Event Handler to HTML Element Using JavaScript
React Router Doesn't Work in Aws S3 Bucket
How to Write Your Own Custom Legends for Google Line Chart/ Google Line Chart Legend Manipulation
Is There Any Difference Between Declared and Defined Variable
Finding Closest Element Without Jquery
JavaScript - Are Dom Redraw Methods Synchronous
Add Onclick Event to Newly Added Element in JavaScript
How to Check If the Url Contains a Given String
Iterate Over Object Literal Values
Displaying a Number in Indian Format Using JavaScript
JavaScript Inheritance: Object.Create VS New
Can You Do Desktop Development Using JavaScript
In JavaScript/Jquery What Does (E) Mean
What Is {This.Props.Children} and When You Should Use It
Injecting JavaScript Variable Before Content Script
Select All Contents of Textbox When It Receives Focus (Vanilla Js or Jquery)