How to Uniquely Identify HTML Elements without IDs?

Viewed 33

Currently working on an issue where I need to be able to quickly, and accurately identify each element within an HTML DOM. The problem is that I do not have the ability to interact with any of the server side or client side javascript, so I cannot simply add IDs to elements. The site can also be dynamic (like a react app) so elements may be added/removed/moved throughout the session, making this quite difficult. I am able to add scripts on top of the app, but not modify what is already there.

I thought using some combination of XPath and HTML attributes would work, but overall the solution seems very messy, and not 100% accurate. For example, in the HTML snippet below, it is not possible (to my knowledge) to uniquely identify the div elements in the tree.

<head>
  <div>hello</div>
  <div>world</div>
</head>

An XPath search of "/head/div" would return both divs, and since they have no attributes, there is no way to uniquely identify one or the other.

1 Answers

First of all, you should not use a <div> inside the <head> tag.

I suggest using a selector like querySelector or querySelectorAll for picking the dom element you want to.

Here's an example using your code:

const mySecondDiv = document.querySelector('head div:nth-child(2)')

As long as you don't have control of how and when the markup changes, your selector could become obsolete/invalid fast. I should say that whatever solution you have will depend on the markup, unfortunately.

Related