How to get CSS selector of an element?

1,453 views
Skip to first unread message

Himawan Anindya Putra

unread,
Sep 2, 2017, 1:50:53 PM9/2/17
to chrome-debugging-protocol
All, 

How do we get CSS selector of an element, such as "#owl-newproducts > li:nth-child(4) > div" ? is there a way?

Thanks!

Andrea Cardaci

unread,
Sep 3, 2017, 12:34:42 PM9/3/17
to chrome-debugging-protocol

Himawan Anindya Putra

unread,
Sep 3, 2017, 10:18:46 PM9/3/17
to chrome-debugging-protocol
Hi Andrea,

Thanks for your reply.

What i mean is if i have a node (or nodeid) how can i get the css path/selector for that particular node.

Andrea Cardaci

unread,
Sep 4, 2017, 8:55:30 AM9/4/17
to chrome-debugging-protocol
AFAIK that's not easily achievable, not even in plain JavaScript as (please correct me if I'm wrong) there's not a unique CSS selector/XPath for each element.

Anyway, if you manage to obtain a working JavaScript solution (meaning, browser-side) you can use Runtime.evaluate to execute it.

Himawan Anindya Putra

unread,
Sep 4, 2017, 8:47:07 PM9/4/17
to chrome-debugging-protocol
Hi Andrea,

Yes you are right, there is not a unique path, but for sure there is at least one path to that particular node.

In Chrome for Desktop, if I enable Developer Tools, and then view Element Inspector, I can right click on a particular element, for example a DIV or a SPAN, then it will show option to "Copy Selector". Can i access/execute that function from Headless Chrome?

Thanks!

Andrea Cardaci

unread,
Sep 5, 2017, 8:10:05 AM9/5/17
to chrome-debugging-protocol
I see, you can take a look at the source code to figure out how DevTools is implementing this feature. It seems that it's not part of the protocol, rather this feature is implemented by manually walking the DOM.

My suggestion is to find a good JavaScript (browser-side) solution and use Runtime.evaluate to execute it.

Hope it helps.


Andrea

Himawan Anindya Putra

unread,
Sep 6, 2017, 12:20:43 AM9/6/17
to chrome-debugging-protocol
Hi Andrea,

Yes, it does help... Will also look at the code.

Thanks! 

donald.br...@gmail.com

unread,
Oct 29, 2017, 4:33:55 AM10/29/17
to chrome-debugging-protocol
For anyone interested in this topic, the source code implementing the "Copy Selector" functionality in Chrome Dev Tools is in the Components.DOMPresentationUtils.cssPath function (https://github.com/ChromeDevTools/devtools-frontend/blob/master/front_end/components/DOMPresentationUtils.js). This function takes the starting node (the node which is right clicked in the UI) and a flag specifying whether to optimize the selector or not.

Donald
Reply all
Reply to author
Forward
0 new messages