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?
To access an HTML element without an ID with JavaScript, we can use document. querySelector . to add a div with an h1 element in it. We use the '#header-inner h1' select to select the h1 element inside the div with ID header-inner .
In CSS, to exclude a particular class, we can use the pseudo-class :not selector also known as negation pseudo-class or not selector. This selector is used to set the style to every element that is not the specified by given selector. Since it is used to prevent a specific items from list of selected items.
function fullPath(el){ var names = []; while (el.parentNode){ if (el.id){ names.unshift('#'+el.id); break; }else{ if (el==el.ownerDocument.documentElement) names.unshift(el.tagName); else{ for (var c=1,e=el;e.previousElementSibling;e=e.previousElementSibling,c++); names.unshift(el.tagName+":nth-child("+c+")"); } el=el.parentNode; } } return names.join(" > "); } console.log( fullPath( $('input')[0] ) ); // "#search > DIV:nth-child(1) > INPUT:nth-child(1)"
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.
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:
> UTILS.cssPath(node)
For implementation example see css_path.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With