Posted By

axolx on 10/17/10


Tagged


Versions (?)

Javascript add/remove/toggle class API


 / Published in: JavaScript
 

URL: http://www.html5rocks.com/tutorials/dnd/basics/

These are handy when not using a library

  1. Element.prototype.hasClassName = function(name) {
  2. return new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)").test(this.className);
  3. };
  4.  
  5. Element.prototype.addClassName = function(name) {
  6. if (!this.hasClassName(name)) {
  7. this.className = this.className ? [this.className, name].join(' ') : name;
  8. }
  9. };
  10.  
  11. Element.prototype.removeClassName = function(name) {
  12. if (this.hasClassName(name)) {
  13. var c = this.className;
  14. this.className = c.replace(new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)", "g"), "");
  15. }
  16. };

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: nicholaslowman on April 8, 2011

Hi Axolx,

I noticed that if for some crazy reason you had the same classname in triplicate or more your 'replace' regex would fail, i.e. class="nick nick nick nick nick", only the 1st, 3rd and 5th elements would be selected so I though you could possible use look-behinds/aheads below rather than non-capturing groups

RegExp("(?

Posted By: nicholaslowman on April 8, 2011

RegExp('(?

Posted By: nicholaslowman on April 8, 2011

I would post the code but it doesn't want to let me:(

You need to login to post a comment.