0

I am trying to click on a specific descendent of an element. I have done gotten the ancestor by ng-class because it does not have an id.

yes = document.querySelectorAll('[ng-controller = "inventoryController"]')

Now that I have the ancestor I want, I want to get the descendent. Once again, they element does not have an id, so I use ng-src to get it.

yes2 = document.querySelectorAll('[ng-src = "link.com/link/here"]')

So How would I use this code to click on the descendent? something like this?

yes[1].yes2[0].click
isherwood
  • 58,414
  • 16
  • 114
  • 157
Piggy
  • 67
  • 7
  • Does this answer your question? [How do I programmatically click on an element in JavaScript?](https://stackoverflow.com/questions/809057/how-do-i-programmatically-click-on-an-element-in-javascript) – Taxel Jun 17 '21 at 14:11
  • I'm confused; you say you're getting the "descendent", but you use `document.querySelectorAll`, which gets all of the elements that match the selector in the document. If you want the descendants of the elements in `yes`, you would need to iterate over `yes` and do `querySelectorAll` off of those. – Heretic Monkey Jun 17 '21 at 14:12
  • @Taxel The question isn't really about the clicking, it's about the selecting. – Barmar Jun 17 '21 at 14:13
  • @Barmar oops, I did not see that they used `document.querySelectorAll` instead of `yes.querySelectorAll` – Taxel Jun 17 '21 at 14:16
  • Does this answer your question? [How to trigger ngClick programmatically](https://stackoverflow.com/questions/22447374/how-to-trigger-ngclick-programmatically) – Kinglish Jun 17 '21 at 15:48
  • This is angularJS - which has it's own methods for DOM manipulation. Of course it's javascript and you can use vanilla to manipulate/affect the DOM but doing so takes events outside of the angular ecosystem and can lead to issues with the parser. What you're looking for is to trigger `ng-click` - see duplicate link – Kinglish Jun 17 '21 at 15:50

1 Answers1

1

First, use querySelector() to get a specific element; querySelectorAll() returns a list of all the matches.

Second, use the result of the first call instead of document to only select its descendants.

yes = document.querySelector('[ng-controller = "inventoryController"]');
yes2 = yes.querySelector('[ng-src = "link.com/link/here"]');

You can also just combine the selectors.

yes2 = document.querySelector('[ng-controller="inventoryController"] [ng-src="link.com/link/here"]');
Barmar
  • 741,623
  • 53
  • 500
  • 612