Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element's CSS selector (when it doesn't have an id)

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?

like image 876
rcphq Avatar asked Jan 03 '11 20:01

rcphq


People also ask

How do I get an element without ID?

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 .

How do you select an element without a class?

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.


2 Answers

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.

like image 84
Phrogz Avatar answered Oct 02 '22 22:10

Phrogz


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

like image 20
tutuDajuju Avatar answered Oct 02 '22 22:10

tutuDajuju