0

Hi am trying to run this but it doesn't work:

document.querySelectorAll('div[2] div ul li a');

if I remove the [2] then it does, or if I query it separately and store it in a variable and then query that variable then it works:

var div = document.querySelectorAll('div')[2];
div.querySelectorAll('div ul li a');

Is there a way to possibly query it all in one go on the chrome console? I did some research and came across something else called nth child and type but I'm curious if this way can work too.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
j obe
  • 1,759
  • 4
  • 15
  • 23
  • Do you mean that `document.querySelectorAll('div[2]');` works for you? – Andersson Nov 06 '18 at 12:38
  • @Andersson nope but ('div')[2] does I'd like to be able to continue adding the other selectors in the same line if possible – j obe Nov 06 '18 at 14:36
  • 1
    Try `document.querySelectorAll('div')[2].querySelectorAll('div ul li a')` if this is what you need – Andersson Nov 06 '18 at 14:48
  • 1
    @Andersson: I've reopened the question. You can go ahead and post that as an answer. – BoltClock Nov 07 '18 at 04:58
  • @Andersson Great that works as I wanted! thanks I'll accept it as an answer. Why the downvotes for the question? – j obe Nov 08 '18 at 12:46

2 Answers2

2

As far as I'm aware, there's no such thing as array indexes for CSS selectors.

Like you mentioned, you could use :nth-child() for this purpose.

document.querySelectorAll('div:nth-child(2) div ul li a');

In this case, the selector matches all a elements in li elements in ul elements in div elements in div elements that are the second child of another element.

Please note that you should keep your selectors as short as possible to improve performance.

  • Thanks, i knew this was is possible, just wondered if the array index way is or not, doesn't seem like it. – j obe Nov 06 '18 at 14:39
  • The second div in the document may not necessarily be the second child of its parent. There can be *multiple* divs that are the second children of their parents across the document. – BoltClock Nov 07 '18 at 04:59
0

If you want consequently select nodes one by one in single query, try

document.querySelectorAll('div')[2].querySelectorAll('div ul li a')
Andersson
  • 51,635
  • 17
  • 77
  • 129