JSFiddle - React, Tailwind, and code Playground

by Kade333

HTML

<script src="https://d3js.org/d3.v3.min.js"></script>
<div id="root">
  <ul>
    <li class="find-me">Lorem</li>
    <li>ipsum</li>
    <li>dolor</li>
    <li class="find-me">sit</li>
    <li class="find-me">amet</li>
  </ul>
  <ul>
    <li class="find-me">consectetur</li>
    <li class="find-me">adipiscing</li>
    <li>elit</li>
  </ul>
</div>

JavaScript

/* Library Functions */
function childMatcher(selector) {
  return function(node) {
    return node.matches(selector);
  };
}

function children() {
  return this.children;
}

function childrenFilter(match) {
  return function() {
    return Array.prototype.filter.call(this.children, match);
  };
}

/**
 * Runs the css selector only on the immediate children.
 * See: https://stackoverflow.com/questions/20569670/d3-selector-for-immediate-children
 * Use: https://github.com/d3/d3-selection/commit/04e9e758c80161ed6b7b951081a5d5785229a8e6
 *
 * Example Input: selectChildren("form")
 */
d3.selection.prototype.selectChildren = function(match) {
  return this.selectAll(match == null ? () => this.children
      : childrenFilter(typeof match === "function" ? match : childMatcher(match)));
}

function childFind(match) {
  return function() {
    return Array.prototype.find.call(this.children, match);
  };
}

function childFirst() {
  return this.firstElementChild;
}

/**
 * Runs the css selector only on the immediate children and returns only the first match.
 * See: https://stackoverflow.com/questions/20569670/d3-selector-for-immediate-children
 * Use: https://github.com/d3/d3-selection/commit/04e9e758c80161ed6b7b951081a5d5785229a8e6
 *
 * Example Input: selectChildren("form")
 */
d3.selection.prototype.selectChild = function(match) {
  return this.select(match == null ? childFirst
      : childFind(typeof match === "function" ? match : childMatcher(match)));
}

/* Example Code */
const root = d3.select("#root")

console.log("test 1:", root.selectChild(".find-me")) // Does not find anything
console.log("test 2:", root.select("ul").selectChild(".find-me")) // Does find something

console.log("test 3:", root.selectChildren(".find-me")) // Does not find anything
console.log("test 4:", root.selectAll("ul").selectChildren(".find-me")) // Does find something