Copy selector structure

1,137 views
Skip to first unread message

Palle Zingmark

unread,
Oct 11, 2011, 8:26:38 AM10/11/11
to Google Chrome Developer Tools
Hi,

I'm not entirely sure this is the correct forum, so please point me in
the right direction if I'm out of place please. :)

I have a feature that I'm missing (or would like to have, or can't
find any way), in the Chrome Developer Tools and I would like to share
my thought on it so see if I'm the only one. Deal?

Here goes:

When inspecting an element, I get a "breadcrumb" in the Developer Tool
statusbar showing the node path to where that element is in the DOM,
it would be a great asset to be able to right-click on an element in
the breadcrumb node path and be able to select "Copy selector
path" (..or something similar).

This would make writing CSS a lot easier when working on a big website
with long nested DOM structures.

Comments, ideas, feedback on this?


Kind regards / Palle Zingmark

Tim Meadowcroft

unread,
Oct 11, 2011, 8:01:38 PM10/11/11
to google-chrome-...@googlegroups.com
Given that when you select an item, the DOM object is assigned to the variable $0 in the console, then you could probably write a little bit of javascript to do this - the below isn't terribly efficient and may not be absolutely correct (parentNode, parentElement?? etc) but it broadly does what you want

crumb = function(node) {
    var idOrClass = (node.id && "#"+node.id) || (""+node.classList && (" "+node.classList).replace(/ /g, "."));
    return node.tagName.toLowerCase() + idOrClass;
  };
crumbPath = function(node) {
  return node.parentNode ? crumbPath(node.parentNode).concat(crumb(node)) : [];
 };

crumbPath($0);

Give it a try and see if it's good enough - you can then just include it in your own page code or put it in an extension to add it as a method to document if you want etc (assuming Paul Irish doesn't tell us its already provided somewhere)

Cheers

--
T

Paul Irish

unread,
Oct 11, 2011, 9:21:34 PM10/11/11
to google-chrome-...@googlegroups.com
http://www.selectorgadget.com/ is a bookmarklet designed for this. Give that a whirl.

That said, code is not very good at determining the best selector for an element, as you might want to group "similar" ones together. Probably too arbitrary to land as a core feature, I'd bet.

Reply all
Reply to author
Forward
0 new messages