The task is to generate a CSS selector path of DOM element by implementation of 'generateSelector' function.
Prerequisites: You must be aware of the basics of HTML, CSS and JavaScript.
Approach:
- First of all, you need to create an index.html file that consists of any markup code like shown in example code.
- Create an app.js file that generate unique CSS selector as given below in the code.
- In the app.js file, when any element is clicked, it will shown in browser console and the generated selector shown on web interface.
Example: In this example, In order to get that selectors are unique, We will use :nth-of-type Selectors. Click on the element to see selector.
Note: This function creates a long, but quite practical unique selector, works quickly.
Comment below if you have any query. I hope you’ll find this article helpful, Thank you for reading :)
Top comments (9)
Had to bookmark this as it could be a great base for a library I work on and I like your implementation.
Here is my implementation, but it generates the the
Xpath
to the item instead of a unique selector.One thing you should steal is the returning early if the item has an ID (as obviously the ID should be unique) just to save on selector complexity.
Thanks :)
Here is some reference: stackoverflow, sitepoint.
I will try it.
Fella, if you are about to create xPath generator, I suggest you to create browser extension for this - I believe there will be a lot of those QA guys who need as fast as possible to get in clipboard such an xpath for e2e testing (yes, I'm talking about those who don't use test ids) - and much better if it defines id or data-id etc. of element and minimize your path just to it
It already uses the id if you look at the code, first thing it checks for and returns early if found.
Plus this is used as part of an analytics package to track clicks, the being able to click on things is just to demonstrate.
If you wanted you could easily turn it into a bookmarklet and have the ID copied to the clipboard, no need to build a browser extension for something so simple, especially when you can get the Xpath with developer tools really easily.
Open Devtools -> select element in DOM -> right click: copy -> copy selector. Voila. :)
But yeah if you want dynamically create CSS selectors maybe not onclick but for something else, the functions might come in handy.
Yeah, true. But for demonstrate purpose I used click event 😅
I fix your code like a bit so that it also show
className
andid
That's great!🤙🏻
Also @medv/finder lib can be used.