I am wondering whether thought has been given to allowing selectors beginning with ">" for use with querySelector/All such as:

    " > .sharedClass"

Sometimes one wishes to resolve a precise hierarchy but relative to the current element. Currently, to do so with precision, one must either specify a path starting from the document root, a unique ID, or use other scripting methods.

Having such an option would provide the same convenience for precise access as XPath or to a lesser extent, as JSON, allow.

The following document illustrates the concern--in this case, where we are trying to get only the second span relative to "#div1" but without needing to specify or be aware of the whole document hierarchy:

<!DOCTYPE html><html><head><meta charset="utf-8" /></head><body>

<div id="div1">
    <span class="sharedClass">First</span>
        <span class="sharedClass">Second</span>


  var s = document.querySelector('#div1');

// The following gets both spans instead of the one directly inside that we want
  var relativeSelector = s.querySelectorAll('.sharedClass');
  alert(relativeSelector.length); // 2

// The following gets the desired span, but required us to specify the full path or redundantly express the path to our parent again
  var absoluteSelector = s.querySelectorAll('#div1 > .sharedClass');
  alert(absoluteSelector[0].textContent); // "First"


(Although the use case would be far less common, a path might also begin with ">" when run against documents to allow usage with XML documents where a path was desired relative to the root but without committing to a specific root element.)

It would also be nice to be able to modify the element or elements--e.g., if there were a removeSelector(sel) analogue to the ability to use "delete obj.prop.prop2" on a JSON object, a replaceSelector(sel, el) convenience method, etc..


Reply via email to