diff --git a/src/js/component.js b/src/js/component.js index e56f0ebe63..cd9a85356c 100644 --- a/src/js/component.js +++ b/src/js/component.js @@ -663,6 +663,16 @@ vjs.Component.prototype.triggerReady = function(){ /* Display ============================================================================= */ +/** + * Check if a component's element has a CSS class name + * + * @param {String} classToCheck Classname to check + * @return {vjs.Component} + */ +vjs.Component.prototype.hasClass = function(classToCheck){ + return vjs.hasClass(this.el_, classToCheck); +}; + /** * Add a CSS class name to the component's element * diff --git a/src/js/lib.js b/src/js/lib.js index 1857966d35..1bf56a24bf 100644 --- a/src/js/lib.js +++ b/src/js/lib.js @@ -293,6 +293,17 @@ vjs.isEmpty = function(obj) { return true; }; +/** + * Check if an element has a CSS class + * @param {Element} element Element to check + * @param {String} classToCheck Classname to check + * @private + */ +vjs.hasClass = function(element, classToCheck){ + return ((' ' + element.className + ' ').indexOf(' ' + classToCheck + ' ') !== -1); +}; + + /** * Add a CSS class name to an element * @param {Element} element Element to add class name to @@ -300,7 +311,7 @@ vjs.isEmpty = function(obj) { * @private */ vjs.addClass = function(element, classToAdd){ - if ((' '+element.className+' ').indexOf(' '+classToAdd+' ') == -1) { + if (!vjs.hasClass(element, classToAdd)) { element.className = element.className === '' ? classToAdd : element.className + ' ' + classToAdd; } }; @@ -314,7 +325,7 @@ vjs.addClass = function(element, classToAdd){ vjs.removeClass = function(element, classToRemove){ var classNames, i; - if (element.className.indexOf(classToRemove) == -1) { return; } + if (!vjs.hasClass(element, classToRemove)) {return;} classNames = element.className.split(' '); diff --git a/test/unit/lib.js b/test/unit/lib.js index 0376661cc0..2f9329dcab 100644 --- a/test/unit/lib.js +++ b/test/unit/lib.js @@ -82,6 +82,14 @@ test('should add and remove a class name on an element', function(){ ok(el.className === 'test-class2', 'removed first class'); }); +test('should read class names on an element', function(){ + var el = document.createElement('div'); + vjs.addClass(el, 'test-class1'); + ok(vjs.hasClass(el, 'test-class1') === true, 'class detected'); + ok(vjs.hasClass(el, 'test-class') === false, 'substring correctly not detected'); + +}); + test('should get and remove data from an element', function(){ var el = document.createElement('div'); var data = vjs.getData(el);