Skip to content

Request for support of console $ and $$ #43

@coolaj86

Description

@coolaj86

Will you add exports (or however you call it) for $ and $$, just as you have for ParentNode?

Rationale

$ and $$ are native to the browser, just like document.querySelector and document.querySelectorAll.

They are different in that

  • they accept a ParentNode as an optional second parameter (the default being document)
  • $$ returns a JavaScript Array rather than a NodeList

Since it's very common to use $ and $$ in this way, I hope it makes sense to include them here as well.

Implementation

/**
 * Select first matching element, just like console $
 * @param {String} cssSelector
 * @param {ParentNode} [$parent=document]
 */
function $(cssSelector, $parent = document) {
  let $child = $parent.querySelector(cssSelector);
  return $child;
}

/**
 * Select all matching child elements as a JS Array, just like console $$
 * @param {String} cssSelector
 * @param {ParentNode} [$parent=document]
 */
function $$(cssSelector, $parent = document) {
  let $children = $parent.querySelectorAll(cssSelector);
  let children = Array.from($children);
  return children;
}

Native to Browser, No JavaScript Loaded

As you can see here, the behavior is as I've described. There is no JavaScript on example.com, and all browsers that I'm aware of have the same implementation - both Firefox and everything else (Chromium- or Webkit-based).

Screenshot 2024-08-29 at 4 08 46 PM

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions