3

Suppose I do the following:

var elems = document.querySelectorAll('div *');

where div is some arbitrary div, like the following:

<div>
   <select>
      <option>Opt1</option>
      <option>Opt1</option>
      <option>Opt1</option>
      <optgroup>
          <option>Opt1</option>
          <option>Opt1</option>
          <option>Opt1</option>
      </optgroup>
   </select>
</div>

My question now is, what will elems be? Did the Javascript standard specify a way on doing these, or is this just left to the implementors.

Other way of putting it, How does Javascript traverse the nodes. Will it traverse it in a DFS (Depth first seach) manner in which I'm guaranteed a perfectly flattened nodes?

  • All elements with a parent (immediate or distant) that is a div - it's the same as a CSS selector – MDEV Jun 17 '15 at 19:06
  • 1
    Um, just try it and see what it produces? –  Jun 17 '15 at 19:23
  • And read [`document.querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) documentation. – David Thomas Jun 17 '15 at 19:26

3 Answers3

1

'elems' will be a non-live NodeList of element objects. Traversal will be DFS (depth first search)

docs

HelloWorld
  • 2,480
  • 3
  • 28
  • 45
0

Its more a choice of the implementer in how you want to implement your javascript variables and methods. If you specify a variable equal to div and the wildcard character, you're going to return everything that is recognized including Null's within the div. Wildcard serves as an indiscriminate catch all. Try it out and see what your result is in the console when you attempt to run a function referencing your elem variable.

Alex
  • 443
  • 3
  • 18
  • What does "null within the div" mean? –  Jun 17 '15 at 19:23
  • In this case, null being empties, if your div has nothing in it, then that would be considered a null as opposed to if you have something such as a list in your div and you specify the list in place of the wildcard character. – Alex Jun 17 '15 at 19:28
  • I think you're confused. If the div has nothing in it, then there are no elements to return. I have no idea how one could have an "array in your div". –  Jun 17 '15 at 19:29
0

It will list all of the elements inside the div, not just the direct descendants (select). There will not, however, be any hierarchy and the list will be flattened, so that all elements at any depth are available immediately.

The response would look like this (a NodeList object which is 'Array-like'):

NodeList [ select, option, option, option, optgroup, option, option, option ]

MDN docs page

MDEV
  • 10,730
  • 2
  • 33
  • 49