How to find a specific class name of element when there are multiple classes?

I have some DIVs on a page. Each has 3 classes: grid_#, push_# and pull_# where # is an actual number.

I need to replace each class separately, i.e. remove class='grid_1' and replace it with class='grid_14'.

I'm using a select list to choose the new class. I need the name of the old class so I can remove it.

Through trial and error, I've found that as long as an element has only one class, I can get it using

var old = document.getElementById('elementId');
var old_class = old.className;

When I try to get the class name from a DIV with multiple classes, I get nothing. Not undefined, not object, just blank. I've tried var old_class = old.className[0]; among other things, but that gives me undefined.

The current plan is to use regex to match the old class name to a list of possible classes, giving me a var with the class name to be removed. Being new to javascript I'm sure there is a better way to do it. Any suggestions are more than welcome.

I've just begun this project, but you can find it here if it would help.

Thanks, Mark

EDIT: Changed title of question

Answers:

Answer

If element has multiple classes, you need to use split:

var old = document.getElementById('elementId');
var old_class = old.className.split(' ')[0]; // first class

What split does is that it creates an array by splitting string (class in this case) which you can later access by its index eg [0] for first class.

If element has just one class, you simply use className:

var cls = old.className;

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.