add and subtract additional classes

2019-08-10 02:34发布

问题:

im trying to add and subtract a class using java script im also using multiple classes here is my code

function enlargegreen() {

    document.getElementByClassName('playlist-player').className += "enlarge";
    document.getElementByClassName('playlist-player').className -= "shrink";

}
<div  class="playlist-player shrink green" onmousedown="enlargegreen()" ></div>

Im trying to subtract the shrink part and replace it with enlarge

回答1:

$(".playlist-player").addClass("green test2").removeClass("playlist-player");

Fiddle

About addClass()

About removeClass()

I made a quick fiddle where i used addClass() and removeClass() in my example. A little about both :

1 ) removeClass() : Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

2 ) addClass() : Adds the specified class(es) to each of the set of matched elements.



回答2:

If jQuery is an option you could simply use addClass (http://api.jquery.com/addClass/) and removeClass (http://api.jquery.com/removeClass/)

It would then look like:

$('.playlist-player').addClass('enlarge');
$('.playlist-player').removeClass('shrink');


回答3:

Here are a few simple js routines:

function addClass( element, name, remove ){
  if ( element.className ) {
    var re = new RegExp(
      '(^|\\s+)' + 
      name.replace(/([^a-zA-Z0-9])/gi, '\\$1') + 
      '(\\s+|$)',
      'g'
    );
    if ( remove ) {
      element.className = element.className.replace( re, '' );
    }
    else if ( !re.test( element.className ) ) {
      element.className += ' ' + name; 
    }
  }
  else if ( !remove ) {
    element.className = name;
  }
};

function removeClass( element, name ){
  return addClass( element, name, true );
};

The above doesn't make a check for any special characters that might break the RegExp as part of the class name. But then again, in my opinion, you should only really have _ or - beyond letters and numbers.

update

I've added a bit of protection now, it should escape any non-alphanumeric character.

update 2

As zzzzBov correctly stated there was an error with not matching the end of the class name which should now be rectified. It also now checks before adding a class to make sure one didn't exist previously. I have also removed case-insensitivity.

I would be interested to know what issues name.replace(/([^a-zA-Z0-9])/gi, '\\$1') could cause, because apart from excessive escaping I'm not certain what could be a problem — within reason — this information would be of use to those finding this QA in the future.



回答4:

You don't have a class named playlist-player. You have a class named playlist-player shrink green and your class names should not have spaces. And I think you should be using getElementsByClassName.