阿里巴巴在线考试,前端测试题 genCssSelector 选择器方法
发布于 5 个月前 作者 1160007652 1673 次浏览 来自 分享
var genCssSelector = function () {
    //you code here
    let ele = arguments[0];
    let parentEle = ele.parentNode;
    let CSelector = ele.tagName.toLowerCase();
    while (parentEle.nodeName.toLowerCase() !== '#document') {
        if (parentEle.id !== '') {
            CSelector = '#' + parentEle.id + ' ' + CSelector;
            parentEle = parentEle.parentNode;
            continue;
        } else if (parentEle.className != '') {
            CSelector = ' ' + CSelector;
            let classList = parentEle.classList || parentEle.className.split(' ');
            for(var i=classList.length-1;i>=0;i--){
                CSelector='.'+classList[i]+CSelector;
                }
            parentEle = parentEle.parentNode;
            continue;
        } else {
            CSelector = parentEle.nodeName.toLowerCase() + ' ' + CSelector;
            parentEle = parentEle.parentNode;
            continue;
        }

    }
    return CSelector;
}
   //点击li时,返回:html body #page .content.main .refer ul li
回到顶部