programing tip

querySelector 직계 자식 검색

itbloger 2020. 10. 5. 07:44
반응형

querySelector 직계 자식 검색


jquery와 같은 기능이 있습니다.

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

문제는 어떻게 똑같이 할 수 querySelector()있습니까?

문제는 >선택기에서 querySelector()부모를 명시 적으로 지정해야한다는 것입니다. 해결 방법이 있습니까?


완전한 답은 아니지만 Google Chrome 및 Safari 7.x (데스크톱 및 모바일 모두)에서 이미 사용할 수 있는 W3C Selector API v.2주시해야합니다 .하지만 제가 테스트 한 한 아직까지는 없습니다. Firefox 및 IE에서.

function(elem) {
  return elem.querySelectorAll(':scope > someselector');
};

당신은 할 수 없습니다. 시작점을 시뮬레이트하는 선택기가 없습니다.

jQuery가이를 수행하는 방식 ( qsa자신이 좋아하지 않는 방식으로 작동 하기 때문에 ) elem은 ID가 있는지 확인 하고 그렇지 않은 경우 일시적으로 ID를 추가 한 다음 전체 선택기 문자열을 생성하는 것입니다.

기본적으로 다음을 수행합니다.

var sel = '> someselector';
var hadId = true;
if( !elem.id ) {
    hadID = false;
    elem.id = 'some_unique_value';
}

sel = '#' + elem.id + sel;

var result = document.querySelectorAll( sel );

if( !hadId ) {
    elem.id = '';
}

이것은 확실히 jQuery 코드가 아니지만, 내가 기억하는 것은 기본적으로 그들이하는 일입니다. 이 상황뿐만 아니라 중첩 된 요소의 컨텍스트에서 선택기를 실행하는 모든 상황에서.

Sizzle의 소스 코드


완료 : 범위 폴리 필

으로 avetisk가 있다 언급 선택자 API를이 개 용도 :scope를 의사-선택합니다.
지원하는 모든 브라우저에서이 작업을 수행하려면 querySelector여기에 polyfill이 있습니다.

(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');

찾고있는 요소의 태그 이름을 알고있는 경우 선택기에서이를 사용하여 원하는 것을 얻을 수 있습니다.

For example if you have a <select> that has <option>s and <optgroups>, and you only want the <option>s that are its immediate children, not the ones inside <optgoups>:

<select>
  <option>iPhone</option>
  <optgroup>
    <option>Nokia</option>
    <option>Blackberry</option>
  </optgroup>
</select>

So, having a reference to the select element, you can — surprisingly — get its immediate children like this:

selectElement.querySelectorAll('select > option')

It seems to work in Chrome, Safari, and Firefox, but didn’t test in IEs. =/


If you want to eventually find direct children (and not e.g. > div > span), you can try Element.matches():

const elems = Array.from(elem.children).filter(e => e.matches('.my-class'))

CLAIM

Personally I would take the answer from patrick dw, and +1 his answer, my answer is for seeking alternative solution. I don't think it deserves a downvote.

Here is my attempt :

function q(elem){
    var nodes = elem.querySelectorAll('someSeletor');
    console.log(nodes);
    for(var i = 0; i < nodes.length; i++){
        if(nodes[i].parentNode === elem) return nodes[i];
    }
}

see http://jsfiddle.net/Lgaw5/8/


That worked for me:

Node.prototype.search = function(selector)
{
    if (selector.indexOf('@this') != -1)
    {
        if (!this.id)
            this.id = "ID" + new Date().getTime(); 
        while (selector.indexOf('@this') != -1)
            selector = selector.replace('@this', '#' + this.id);
        return document.querySelectorAll(selector);
    } else 
        return this.querySelectorAll(selector);
};

you will have to pass the @this keywork before the > when you want to search for immediate children.


The following is a simplified, generic method for running any CSS selector query over only direct children - it also accounts for combined queries, like "foo[bar], baz.boo":

var count = 0;
function queryChildren(element, selector) {
  var id = element.id,
      guid = element.id = id || 'query_children_' + count++,
      attr = '#' + guid + ' > ',
      selector = attr + (selector + '').replace(',', ',' + attr, 'g');
  var result = element.parentNode.querySelectorAll(selector);
  if (!id) element.removeAttribute('id');
  return result;
}


*** Example Use ***

queryChildren(someElement, '.foo, .bar[xyz="123"]');

There’s a query-relative lib, which is quite handy replacement for query-selector. It polyfills children selector '> *' and :scope (inc. IE8), as well as normalizes :root selector. Also it provides some special relative pseudos like :closest, :parent, :prev, :next, just in case.


check if element have id else add random id and do search based on it

function(elem) {
      if(!elem.id)
          elem.id = Math.random().toString(36).substr(2, 10);
      return elem.querySelectorAll(elem.id + ' > someselector');
    };

will do same thing as

$("> someselector",$(elem))

참고URL : https://stackoverflow.com/questions/6481612/queryselector-search-immediate-children

반응형