Javascript add/remove/toggle class API


/ Published in: JavaScript
Save to your folder(s)

These are handy when not using a library


Copy this code and paste it in your HTML
  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. };

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.