How to create CSS path with javascript or jquery?

Any suggestions on how to create a CSS path for an element?

The CSS path is the path of the css selectors needed to identify a specific element, for example, if my html is:

<div id="foo"> <div class="bar"> <ul> <li>1</li> <li>2</li> <li><span class="selected">3</span></li> </ul> </div> </div> 

then the class path to "3" will be div#foo div.bar ul li span.selected

JQuery uses class paths to identify DOM elements and may provide a good solution, but so far I have not been able to find it.

+6
javascript css
source share
2 answers

I do not understand why this is a top-down, good and legitimate question.

here is an example (simplified) of how this can be done

 <div id="a"> <div class="b"> <div><span></span></div> </div> </div> <script> function getPath(elem) { if(elem.id) return "#" + elem.id; if(elem.tagName == "BODY") return ''; var path = getPath(elem.parentNode); if(elem.className) return path + " " + elem.tagName + "." + elem.className; return path + " " + elem.tagName; } window.onload = function() { alert(getPath(document.getElementsByTagName("SPAN")[0])); } </script> 
+9
source share

Create element css path

Full path Ex: body / footer.Footer / div.Footer-inner / ul.FooterList / li.FooterList_item

 function getFullCSSPath(element) { if (element.tagName == 'HTML') return ''; if (element===document.body) return getShortCSSPath(element); // To calculate position among siblings var position = 1; // Gets all siblings of that element. // Gets the parent tree node of the current tree node. var siblings = element.parentNode.childNodes; for (var i = 0; i < siblings.length; i++) { var sibling = siblings[i]; // Checks Siblink with passed element. if (sibling === element) { var elemCssPath = getShortCSSPath(element); //console.log('====='+elemCssPath); //console.log('-----'+position); return getFullCSSPath(element.parentNode)+'/'+elemCssPath; // using recursion to find its parents untill root element HTML } // if it is a siblink & element-node then only increments position. var type = sibling.nodeType; if (type === 1 && sibling.tagName === element.tagName) position++; } } 

Short Path Ex: li.FooterList_item

 function getShortCSSPath(element) { var path = element.tagName.toLowerCase(); if(element.id) path += "#" + element.id; if(element.className) path += "." + element.className; return path; } 

Test

 var elem = document.getElementsByTagName('div')[20]; console.log('Full Path : '+getFullCSSPath(elem)); console.log('Short Path : '+getShortCSSPath(elem)); 

To generate Xpath

0
source share

All Articles