By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,953 Members | 1,054 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,953 IT Pros & Developers. It's quick & easy.

set dom element class (if element was dynamically created)

P: n/a
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

Jan 25 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a
span.className = "span_class";

Jan 25 '06 #2

P: n/a
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);

Jan 25 '06 #3

P: n/a
ted benedict wrote:
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>


--
Rob
Jan 27 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.