0

I am wondering if I can directly (like window.document.foo.bar) access to a particular node with JavaScript with the given DOM information.

I would start the question with the reason why I need this, but you can skip it.

  1. Why I need to do this.

I want to know all eventListeners associated with a DOM object outside of the main HTML using Chrome DevTools Protocol. This requires RemoteObjectId, and to get this I need to run Runtime.Evaluate over the target object.

  1. Example
<html>
  <head>
  </head>
  <body>
    <div>
      <p>...</p>
      <p>...</p>  <-- target object
      <p>...</p>
    </div>
    <div>
    </div>
  </body>
</html>

In the code above, I want to access the target object.

I can identify the location of the target object at main HTML side, by recursively checking parents and siblings starting from the target object.

The identified location is like; body.div(1st).p(2nd)

How can I do this with an evaluation? Runtime.Evaluate(window.document.body.div.p) accesses very first p, not the target p. But I cannot find a way to go the second one to get the remoteObjectId of the target p.

Jin
  • 304
  • 2
  • 10
  • @Yogi I could not find an answer from hours of searching, except for some approaches using Puppeteer, which I would not like to do as it changes the entire structure of my toolset. Could you give me a link if you have seen any question similar to this? – Jin Jul 24 '23 at 18:02

1 Answers1

0

why don't you just use querySelector() and nth-child() for accessing the specific p?

  • Thank you for the answer. nth-child would be a good option - I forgot that as I have been stick to the pure JavaScript. Could you think of other options without JQuery or CSS? – Jin Jul 24 '23 at 19:42
  • first give your target a class name like `target` then you can use `querySelectorAll("p")` for accessing all `p`'s after that use an `forEach` to iterate over the array from `querySelectorAll()` and inside that `forEach` use an `if` to check if iterated element is equal to target element (use `matches` in if condition) like this `if(iterated p.matches(".target p class name")`,,, if you didn't understand this tell me to write this as an answer.@Jin – scorpian111 Jul 24 '23 at 20:36
  • Dynamically adding a class to selectively retrieve those is actually a good idea under my situation. Thank you for the idea! – Jin Jul 24 '23 at 21:50