1. ホーム
  2. javascript

[解決済み] querySelector search immediate children [重複]。

2022-09-13 03:59:50

質問

jqueryのような関数があります。

function(elem) {
    return $('> someselector', elem);
};

問題は、同じことを querySelector() ?

問題は > のセレクタが querySelector() では、parent を明示的に指定する必要があります。何か回避策はあるのでしょうか?

解決方法はありますか?

スコープポリフィルの完成

として 前方一致 言及 セレクタ API 2 では :scope 擬似セレクタを使用しています。

これをすべてのブラウザで動作させるために、(サポートされている querySelector をサポートする)すべてのブラウザで動作するようにするためのポリフィルは次のとおりです。

(function(doc, proto) {
  try { // check if browser supports :scope natively
    doc.querySelector(':scope body');
  } catch (err) { // polyfill native methods if it doesn't
    ['querySelector', 'querySelectorAll'].forEach(function(method) {
      var nativ = proto[method];
      proto[method] = function(selectors) {
        if (/(^|,)\s*:scope/.test(selectors)) { // only if selectors contains :scope
          var id = this.id; // remember current element id
          this.id = 'ID_' + Date.now(); // assign new unique id
          selectors = selectors.replace(/((^|,)\s*):scope/g, '$1#' + this.id); // replace :scope with #ID
          var result = doc[method](selectors);
          this.id = id; // restore previous id
          return result;
        } else {
          return nativ.call(this, selectors); // use native code for other selectors
        }
      }
    });
  }
})(window.document, Element.prototype);

使用方法

node.querySelector(':scope > someselector');
node.querySelectorAll(':scope > someselector');


歴史的な理由から、私の以前の解決策は

すべての回答に基づいて

// Caution! Prototype extending
Node.prototype.find = function(selector) {
    if (/(^\s*|,\s*)>/.test(selector)) {
        if (!this.id) {
            this.id = 'ID_' + new Date().getTime();
            var removeId = true;
        }
        selector = selector.replace(/(^\s*|,\s*)>/g, '$1#' + this.id + ' >');
        var result = document.querySelectorAll(selector);
        if (removeId) {
            this.id = null;
        }
        return result;
    } else {
        return this.querySelectorAll(selector);
    }
};

使用方法

elem.find('> a');