set dom element class (if element was dynamically created)

T

ted benedict

hi everybody, didn't find this using the search :( this is my problem:
i create a dom element dynamically (<span>) and want to assign a class
attribute to it such that it has some css style, this works in ie, but
not in firefox :( here's the simple code:

<div id="somediv">
</div>

var div = window.document.getElementById("somediv");
var span = window.document.createElement("span");
span.innerHTML = "span";
span.attributes.getNamedItem("class").nodeValue = "span_class";
div.appendChild(span);

so this works well in ie6, but firefox gives this error:
Error: span.attributes.getNamedItem("class") has no properties

if i run this code on a statically defined span (in the html file),
where a class attribute already is set:
<div id="somediv">
<span id="spanspan" class="">
</span>
</div>
changing the class to "span_class" works both in ie and firefox.

how can i fix my above code such that it works in both browsers? it
seems that on newly created dom elements the class attribute isn't even
there (to change it), how can i create it, and then change it?

thanks for your time, all the best
 
T

ted benedict

thanks marss, this solved the problem!

i also found another (a bit longer) solution as an alternative, if it
helps somebody :)

var class_attrib = window.document.createAttribute("class");
class_attrib.nodeValue = "span_class";
span.attributes.setNamedItem(class_attrib);
 
R

RobG

ted said:
thanks marss, this solved the problem!

i also found another (a bit longer) solution as an alternative, if it
helps somebody :)

var class_attrib = window.document.createAttribute("class");
class_attrib.nodeValue = "span_class";
span.attributes.setNamedItem(class_attrib);

'class' is a future reserved word in JavaScript 1.5 (the version most
commonly implemented in modern browsers), hence the use of 'className'
to refer to the HTML element attribute 'class'.

There are proposals to add classes (and hence use the 'class' keyword)
to ECMAScript Ed 4:
<URL:http://www.mozilla.org/js/language/es4/core/classes.html>

and JavaScript 2.0:
<URL:http://www.mozilla.org/js/language/js20/core/classes.html>.

Microsoft has already added classes to JScript .NET.
<URL:http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnclinic/html/scripting07142000.asp>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top