Suppose you want to modify an element with no direct identifiers, but using a similar Xpath:
#js_n6 > div > ul > li:nth-child(4) > a > span > span
You may typically use it within document.querySelector('')
, but there's a catch:
The #js_n6
ID is generated dynamically during each page load (when the webpage is created or refreshed):
During each page load, you receive a different ID like #js-x1
, #js_v9
, #js z4
, #js k1
and so on, while the rest of the Xpath remains constant.
I attempted using a CSS wildcard such as [id^="js"]
for the ID, but it doesn't work effectively as it also targets other elements with similar IDs found by the wildcard.
One example of this can be seen on Facebook.com's messages page. Visit the page with all conversations and execute the following in console:
document.querySelector('.5blh.4-0h').click();
Then, inspect the "Delete" button on the modal menu, and note the Xpath. Refresh the page and observe again to see the issue.
This is just an illustration; I'm not suggesting any scraping nor specifically referring to Facebook, but rather trying to understand a general concept.
In such scenarios, I am curious about how one can target an object without direct identifiers, especially when the Xpath includes a dynamic ID.
Notes:
- In such situations, I do not have control over the website and cannot add identifiers from the server side.