What information about the DOM element will allow JavaScript to identify it (somewhat) uniquely? (for example, when it does not have `id`)

Here is what I'm trying to do: I have a bookmarklet that searches for elements on the current page (it can be any site) and sends a click event to those that match. I have this part of the job.

In some cases, however, nothing matches automatically, and I want to show (by hanging it) which element should be activated, and then save some information about it in localStorage. The next time I use the bookmarklet on this page, I want to get this information to identify the element in the DOM, and then send a click event.

Question: What information should I save in order to be able to identify it? (in most cases, since you can always create a case where it does not work)

In the best case, the specified element will matter id, and I'm ready to go. In some other cases, this is not the case, and I would like to see your suggestions regarding what information and which method should I use to return it.

So far, my idea is to save some properties of the element and traverse the DOM to find elements that match all. Not all properties will work (for example, it clientWidthwill depend on the size of the browser), and not all types of elements will have all the properties (for example, divnode will not matter src), which means that, on the one hand, I cannot blindly save all properties , but on the other hand, I need to either select a limited list of properties that will work for any types of elements (at the risk of losing some useful information), or different cases for different elements (which is not very cool).

Things I thought I could use:

  • id of course
  • className, tagNamewill help, although classNamemost likely it will not be an obvious coincidence in some cases
  • innerHTML ,
  • src ,
  • ( )
  • ...

, " ?", . !

+3
4

, tagName className-combination. innerHTML .

, , .

id = > childs id = > , tagName className-combination (if = > : -)

+1

, @brendan. jQuery DOM, "index" , , DOM .

, , - -

body > :nth-child(3) > :nth-child(0) > :nth-child(4)

, DOM . .., , , , , , , "id" , , , .

+2

. id.

+1
source

How about using the index of the (integer) element inside the DOM? You can scroll through each element on the page load and configure your own attribute for the index ...

var els = document.getElementsByTagName("*");
for(var i = 0, l = els.length; i < l; i++) {
  els[i].customIndex = i;
}
0
source

Source: https://habr.com/ru/post/1735147/


All Articles