View Full Version : setAttribute for multiple attributes question

07-18-2007, 03:37 PM
I have multiple attributes (class, id and title) that is needed to insert into a div together. All I know how to use setAttribute for single attribute. So the question is there an "array" setAttribute method to insert all attributes together into an element OR is there a "after" or "before" setAttribute method I can use to insert an attribute after or before other attribute?



Bill Posters
07-18-2007, 05:46 PM
Just use it as many times as you need to add as many attributes as you need.



However, due to the issues surrounding setAttribute, class and className, it's generally safer (as well as quicker and better supported) to use DOM 0 syntax…


obj.className = 'className';
obj.id = 'idValue';
obj.title = 'titleValue';

rnd me
07-19-2007, 05:21 AM
So the question is there an "array" setAttribute method to insert all attributes together into an element?

There is now,though it uses an object, not an array, but if you preserve order when you construct an array of props, i'm sure you could convert it.

here you go:

function setAttribs(elm, ob) {
var r = [];
var i = 0;
for (var z in ob) {
if (ob.hasOwnProperty(z)) {
catch(er){ elm.setAttribute( z, ob[z])}
return elm;

var dd=document.createElement("div")
setAttribs(dd, {id: "eyeDee", className: "dynamo", title: 'titleValue 1'})

alert(dd.outerHTML) //example to show that attribs took effect (ie only)

you could pass it an anon object like in the example, or (more powerfully) build some template objects, and pass those.
for example:

var Dyno=function(h){
this.style="width:"+(screen.width * 0.8)+"px; height: 120px";
this.title="Dynamic Element Title";
this.id="IDno"+ (Dyno.dynCount++);
}//end Constructor Dyno


var style1=new Dyno('Now is the time for <u>all</u> good men...')

var dd=document.createElement("div")
setAttribs(dd, style1)

works for me. it tries the "DOM0", usually faster method, and if that fails (ex: setting 'style' in firefox) it falls back to the DOM1/2 setAttribute method. i just spent about 10 mins writing this, so i hope it helps you or someone else.