On Tue, May 9, 2017 at 7:57 PM, Steve Litt <slitt@...2357...> wrote:

> The limitations are purely those inherent in CSS selectors in general
> - e.g. that you can only select descendants of your chosen node, not
> its ancestors,

Sounds pretty good to me. If I wanted to cast a wider net, I'd do
document.querySelector('.whatever') instead of

The limitation of not being able to select ancestors can sometimes be a problem if you've got an event handler. Consider this example of a few groups within groups:

<g id="myParent">
  <g onclick="clicked(this);">
    <g class="inner">
      <circle id="circle1" ... />

  <g onclick="clicked(this);">
    <g class="inner">
      <circle id="circle2"... />

In your event handler you get a handle to the clicked group, but if you wanted to get a handle to the parent element ("myParent"), there's no way to use querySelector() to get to it. E.g.

function clicked(oGroup) {
  var c = oGroup.querySelector(".inner > circle");   // Gets the circle - selecting into the tree is fine
  var c = oGroup.querySelector("g > circle");         // Does the same
  var c = oGroup.querySelector("circle");               // So does this (in this case)
  var c = oGroup.querySelector("g circle");            // As does this (in this case), but a little less efficiently

  // If I want to get the parent group, this would be a nice option...
  var g = oGroup.querySelector("this < g");  // There's no "this" in CSS, and no "<" as a parent selector. This will fail.

  // Instead I end up doing this...
  var g = oGroup.parentNode;

In this simple example that's not too bad, but when you start getting more complex DOM structures, you can end up having to maintain code that has "this.parentNode.parentNode.nextElementSibling.parentNode" and similarly fragile structures.

So yes, you can use document.querySelector() to select from the entire document, or node.querySelector() to restrict the selection, but depending on your "starting point" it you might not have the luxury of choice. It's generally a lot easier going down into the tree than walking back up it.

When you clued me in to 'this', it opened a world of possibilities.

Just be a little careful with "this", as it can change depending on how a function is called. It's often worth logging it out to make sure it actually represents the thing you think it does. This can be a particular problem if you start trying to do anything asynchronously, using setTimeout() or similar.