I'm trying to modify a page through JavaScript/CSS (much like Stylish or Greasemonkey do). This is a very complex page (that I didn't build, or can't modify pre-render), which makes constructing the CSS selector hard to do (manually looking at document structure). How can I achieve this?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
I found I could actually use this code from chrome devtools source to solve this, without that many modifications.
After adding relevant methods from
WebInspector.DOMPresentationUtils
to new namespace, and fixing some differences, I simply call it like so:For implementation example see
css_path.js
you can use for css first-child pseudo classes if the element is a first child in a div table or body..etc
you can use jquery's nth child() function.
http://api.jquery.com/nth-child-selector/
example from jquery.com
my 2 cents if I understood the question correctly.
Check this CSS selector generator library @medv/finder
Example of generated selector:
This seems to be what you are asking for
, but you may realize that this is not guaranteed to uniquely identify only one element. (For the above example, all the sibling inputs would be matched as well.)Edit: Changed code to use
nth-child
instead of CSS classes to properly disambiguate for a single child.Use FireFox with FireBug installed.
Output for the permalink to this answer (XPath):
CSS Path:
But regarding this comment:
If that is your intent, there may be an easier way through JavaScript:
The last line may need to be implemented differently for different browsers. Did not test.