views:

312

answers:

5

I am trying to change the class of a element with Javascript using the below code:

parent.document.getElementById('<?php echo $markid ?>').class = 'unlistened';

Not having much luck though. How do I do this properly?

+10  A: 

.className rather than .class

Justin Wignall
d'oh! beat me to it by 20 seconds :p
peirix
beat me too ...
edeverett
YES. Thanks so much.
ian
+5  A: 

className should do the trick (:

peirix
+6  A: 

Use .className instead of .class

Class is a reserved word in JS so it's changed to className. A few other HTML attributes are changed in a similar way. "for" changes to "htmlFor" for instance.

edeverett
A: 

Use jQuery...

$("tagname").addclass("unlistened");

http://docs.jquery.com/Attributes/addClass

rikh
A: 

Just a tip, it's much easier to use jQuery if you're doing JavaScript these days, since it's so much easier and only really requires you to have good CSS knowledge (for selectors and so on)

You'd do $(selector).addClass('myclass');

And retrive it like so:

$(selector).attr('class');

Oh yes, and please note if you're using a mixture of classes on any element, the above function will return them all delimited by a space (like you'd define in the HTML class attribute.) If you want to check if a particular class exists, do this:

$(selector).hasClass('class');

That's the basics of class manipulation with jQuery. Check out http://docs.jquery.com/ for the rest.

Will Morgan
I'm not sure why people are downvoting my answer. It's a helpful and friendly suggestion...
Will Morgan
i didnt downvote but i would imagine because there was no mention of looking for a solution in jQuery, rather just pure JS.
Darko Z
If you are not using jquery already, this is not a helpful answer if the plain javascript sollution is just as easy (in this case, even easier than your suggestion...). By the way - I did not downvote you...
awe
Chances are if you're modifying the DOM you'd be using a library to do so.Call it lazy but I'd rather include a 50k library and write elegant code than bother reinventing the wheel.
Will Morgan