1

When I have the Web Developer tool open and inspecting a page, sometimes I wish to select an element and copy (i.e. grab the entire text) of its CSS selector.

I mean this:

screenshot

For some reason the text in that box is not selectable, and right click shows no menu or options.

Is there a way to grab or export that text so I can process it in my code?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
RocketNuts
  • 9,958
  • 11
  • 47
  • 88
  • Right click on the element and pick from dropdown the 'edit as HTML'. There you can copy the whole element with it's entities. – lortschi Jan 21 '21 at 17:07
  • @lortschi I don't mean the html tag with its attributes, I mean the DOM 'stack' or selector. Like `div.someclass > span#specialid > p > div > strong.otherclass` i.e. the whole list of preceding parent DOM elements that the current element is a child of. – RocketNuts Jan 21 '21 at 21:20
  • It is normally not wise to use the whole selector path, neither for using it in your style sheet nor UI testing. Firstly, just a little change in your DOM structure will make the selector invalid, and secondly, it makes selecting the element slow from a browser engine's perspective. Therefore, you should rather try to keep your selectors as short as possible e.g. by using id and/or class selectors. – Sebastian Zartner Jan 22 '21 at 12:00
  • 1
    @SebastianZartner I know, I typically don't do this, but in some cases I would like to have the whole DOM 'path' (or what's the right term?) so I can pick some key elements that are uniquely identyfing for the element I need, and still likely to be somewhat resistant to layout changes. – RocketNuts Jan 22 '21 at 14:20

1 Answers1

3

Right-click the element in the inspector, choose the Copy submenu, and each browser gives you slightly different options:

  • Chrome (and other Chromium-based browsers including the new Microsoft Edge) gives you the option to copy the selector, which produces a somewhat optimized but still fairly long selector that will uniquely identify the element.

  • Firefox gives you two options: "CSS Selector" that functions mostly the same as Chrome but gives you a much more optimized selector, and "CSS Path" that gives you the same as what you're pointing to in your screenshot, the entire path to that element starting from the root. "CSS Path" is designed for web testing tools but it's probably excessive for most other use cases, which I'm guessing is why Chrome doesn't have a similar feature.

Check out these other answers in which I explain a bit more how these features work:

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356