原生js 操作class 原生js获取父元素

原生js判断有没有class
hasClass = (ele, cName) => {
        let reg = new RegExp("(?:^| +)" + cName + "(?: +|$)", "g");
        if(ele.className === undefined){
            return false;
        }else{
            return reg.test(ele.className);
        }

    }
原生js移除class
    removeClasss = (ele,txt) => {
        let reg = new RegExp("(?:^| +)" + txt + "(?: +|$)", "g");
        if(this.hasClass(ele, txt)){
            ele.className = ele.className.replace(reg, "");
        }
    }
原生js添加class
    addClasss = (ele,txt) => {
        let str =  ele.className;
        ele.className += ' ' + txt;
    }
原生js获取某个父节点(查找class名为ant-list-item的父元素)
getParent = (ele) => {
        let targetParent = ele.parentNode;
        while (!this.hasClass(targetParent,'ant-list-item')) {
            targetParent = targetParent.parentNode;
        }
        return targetParent;
    }

 

posted @ 2021-02-04 16:38  dongxiaolei  阅读(3802)  评论(0编辑  收藏  举报