Getting Element Path for selector

前端 未结 4 918
既然无缘
既然无缘 2020-12-16 04:59

Running into a spot of trouble and basically trying to create a variable which can be used as a selector. eg

$(\'a\').click(function(){
   var selector = $(t         


        
4条回答
  •  旧时难觅i
    2020-12-16 05:30

    Modified version of @jcern`s fantastic code.

    Features:

    • If the element has an id: show only #elementId
    • If no id is present: show element.className
    • If no class is present: show element with it's innerHtml appended (if any)
    • Skip the and elements to shorten output
    • Does not rely on jQuery
    function dompath(element) {
        var path = '',
        i, innerText, tag, selector, classes;
    
        for (i = 0; element && element.nodeType == 1; element = element.parentNode, i++) {
            innerText = element.childNodes.length === 0 ? element.innerHTML : '';
            tag = element.tagName.toLowerCase();
            classes = element.className;
    
            // Skip  and  tags
            if (tag === "html" || tag === "body")
                continue;
    
            if (element.id !== '') {
                // If element has an ID, use only the ID of the element
                selector = '#' + element.id;
    
                // To use this with jQuery, return a path once we have an ID
                // as it's no need to look for more parents afterwards.
                //return selector + ' ' + path;
            } else if (classes.length > 0) {
                // If element has classes, use the element tag with the class names appended
                selector = tag + '.' + classes.replace(/ /g , ".");
            } else {
                // If element has neither, print tag with containing text appended (if any)
                selector = tag + ((innerText.length > 0) ? ":contains('" + innerText + "')" : "");
            }
    
            path = ' ' + selector + path;
        }
        return path;
    }
    

提交回复
热议问题