-5

I would like to prevent duplicate classnames on an element using JavaScript.

When I run the following code, I get the classname "Test 1" twice.

Here's my HTML:

<body>
    <div id="foo">Hey</div>
</body>

and my Javascript:

function addClass(element, myClass) {
   var add = element.className += ' ' + myClass; 
}

addClass(foo,'Test1');
addClass(foo,'Test1');
addClass(foo, 'Test2');

I would like my result to be:

<div id="foo" class=" Test1 Test2">Hey</div> 

and not

<div id="foo" class=" Test1 Test1 Test2">Hey</div> 

Is there any way I can achieve this?

dsgriffin
  • 66,495
  • 17
  • 137
  • 137

3 Answers3

3

Use the string.contains() method when adding the class; try something like

function addClass(element, myClass) {
   if(!element.className.contains(myClass))
       element.className += ' ' + myClass; 
}

EDIT

Use string.split(" ") to break the class names up (to avoid matching partial class names), then use indexOf to check to see if the class has been added already. Something like

function addClass(element, myClass) {
   if(element.className.split(" ").indexOf(myClass)==-1)
       element.className += ' ' + myClass; 
}
alexkonradi
  • 750
  • 5
  • 5
3

jsFiddle here.

Use indexOf() to see if it already has that class. Note that the solution by itself would cause problems when having classes that contain part of another, so I've slightly changed it (New solution is a little ugly but meh)

function addClass(element, myClass) {
   if((" " +element.className+ " ").indexOf(" "+myClass+" ") == -1)
       element.className += ' ' + myClass; 
}
dsgriffin
  • 66,495
  • 17
  • 137
  • 137
0

I suppose if you are adding a class you want that class to have precedence- if it exists already but was superceded in the cascade by another class, move the old instance to the end of the class definitition-

function addCLass(who,cname){
    var rx= RegExp('\\b'+cname+'\\b','g'),
    C=who.className.replace(rx,'').split(/\s+/).push(cname);
    who.className= C.join(' ');
}
kennebec
  • 102,654
  • 32
  • 106
  • 127