12

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?

5 Answers 5

23

.className rather than .class

Sign up to request clarification or add additional context in comments.

1 Comment

d'oh! beat me to it by 20 seconds :p
9

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.

Comments

5

className should do the trick (:

Comments

2

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.

4 Comments

I'm not sure why people are downvoting my answer. It's a helpful and friendly suggestion...
i didnt downvote but i would imagine because there was no mention of looking for a solution in jQuery, rather just pure JS.
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...
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.
-3

Use jQuery...

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.