3 回答
TA贡献1752条经验 获得超4个赞
/**
* Method that checks whether cls is present in element object.
* @param {Object} ele DOM element which needs to be checked
* @param {Object} cls Classname is tested
* @return {Boolean} True if cls is present, false otherwise.
*/
function hasClass(ele, cls) {
return ele.getAttribute('class').indexOf(cls) > -1;
}
/**
* Method that adds a class to given element.
* @param {Object} ele DOM element where class needs to be added
* @param {Object} cls Classname which is to be added
* @return {null} nothing is returned.
*/
function addClass(ele, cls) {
if (ele.classList) {
ele.classList.add(cls);
} else if (!hasClass(ele, cls)) {
ele.setAttribute('class', ele.getAttribute('class') + ' ' + cls);
}
}
/**
* Method that does a check to ensure that class is removed from element.
* @param {Object} ele DOM element where class needs to be removed
* @param {Object} cls Classname which is to be removed
* @return {null} Null nothing is returned.
*/
function removeClass(ele, cls) {
if (ele.classList) {
ele.classList.remove(cls);
} else if (hasClass(ele, cls)) {
ele.setAttribute('class', ele.getAttribute('class').replace(cls, ' '));
}
}
添加回答
举报