I am creating this JS function that creates an element The function takes two parameters strName and objAttributes
function createElement( strName, objAttributes )
{
var elem = document.createElement(strName);
for ( var i in objAttributes )
elem.setAttribute(i, objAttributes[i]);
return elem;
}
This works fine in Fx, but not in MSIE I know that the setAttibute method is buggy and the proposed workaround is
elem.attr = 'val';
But right now I have no idea how to write this inside my loop.
I have tried both elem.style and elem['style'] but none of them works.
Can anyone give me some advice,
thanks in advance
t
I am creating this JS function that creates an element The function takes two parameters strName and objAttributes
function createElement( strName, objAttributes )
{
var elem = document.createElement(strName);
for ( var i in objAttributes )
elem.setAttribute(i, objAttributes[i]);
return elem;
}
This works fine in Fx, but not in MSIE I know that the setAttibute method is buggy and the proposed workaround is
elem.attr = 'val';
But right now I have no idea how to write this inside my loop.
I have tried both elem.style and elem['style'] but none of them works.
Can anyone give me some advice,
thanks in advance
t
Share Improve this question edited Mar 28, 2009 at 1:31 Scott Evernden 40k15 gold badges80 silver badges84 bronze badges asked Mar 28, 2009 at 0:58 ThomasThomas3 Answers
Reset to default 6Use elem[i]
.
function createElement( strName, objAttributes )
{
var elem = document.createElement(strName);
for ( var i in objAttributes )
elem[i] = objAttributes[i];
return elem;
}
You can't just swap setting properties and setAttribute.
You have to be careful with setting properties on an element in place of using setAttribute. Style properties and event handlers need to be carefully written, and those attributes that used to be minimized in html (disabled, multiple, readonly) have browser specific valid values.
Also, if you set element.class="mynewclass", you'll get an error, because class is a reserved javascript word, though it is perfectly safe to use it as a string in a setAttribute assignment. THe property name is '.className', and the proper name for a label's 'for' attribute is 'htmlFor'.
Let jQuery handle the cross-browser nonsense...
$(elem).attr(i, objAttributes[i]);