IT박스

라이브러리를 사용하지 않고 querySelectorAll을 사용할 수없는 경우 속성별로 요소를 가져 오십니까?

itboxs 2020. 7. 15. 07:53
반응형

라이브러리를 사용하지 않고 querySelectorAll을 사용할 수없는 경우 속성별로 요소를 가져 오십니까?


<p data-foo="bar">

당신은 어떻게

document.querySelectorAll('[data-foo]')

querySelectorAll을 사용할 수없는어디 입니까?

적어도 IE7에서 작동하는 기본 솔루션이 필요합니다. IE6에 관심이 없습니다.


getElementsByTagName ( '*')을 실행하고 "data-foo"속성이있는 요소 만 리턴하는 함수를 작성할 수 있습니다.

function getAllElementsWithAttribute(attribute)
{
  var matchingElements = [];
  var allElements = document.getElementsByTagName('*');
  for (var i = 0, n = allElements.length; i < n; i++)
  {
    if (allElements[i].getAttribute(attribute) !== null)
    {
      // Element exists with attribute. Add to array.
      matchingElements.push(allElements[i]);
    }
  }
  return matchingElements;
}

그때,

getAllElementsWithAttribute('data-foo');

사용하다

//find first element with "someAttr" attribute
document.querySelector('[someAttr]')

또는

//find all elements with "someAttr" attribute
document.querySelectorAll('[someAttr]') 

속성별로 요소를 찾습니다. 이제 모든 관련 브라우저 (IE8조차도)에서 지원됩니다 : http://caniuse.com/#search=queryselector


나는 조금 놀아서이 조잡한 해결책으로 끝났습니다.

function getElementsByAttribute(attribute, context) {
  var nodeList = (context || document).getElementsByTagName('*');
  var nodeArray = [];
  var iterator = 0;
  var node = null;

  while (node = nodeList[iterator++]) {
    if (node.hasAttribute(attribute)) nodeArray.push(node);
  }

  return nodeArray;
}

사용법은 매우 간단하며 IE8에서도 작동합니다.

getElementsByAttribute('data-foo');
// or with parentNode
getElementsByAttribute('data-foo', document);

http://fiddle.jshell.net/9xaxf6jr/

But I recommend to use querySelector / All for this (and to support older browsers use a polyfill):

document.querySelectorAll('[data-foo]');

Try this it works

document.querySelector('[attribute="value"]')

example :

document.querySelector('[role="button"]')

That works too:

document.querySelector([attribute="value"]);

So:

document.querySelector([data-foo="bar"]);

Try this - I slightly changed the above answers:

var getAttributes = function(attribute) {
    var allElements = document.getElementsByTagName('*'),
        allElementsLen = allElements.length,
        curElement,
        i,
        results = [];

    for(i = 0; i < allElementsLen; i += 1) {
        curElement = allElements[i];

        if(curElement.getAttribute(attribute)) {
            results.push(curElement);
        }
    }

    return results;
};

Then,

getAttributes('data-foo');

A little modification on @kevinfahy 's answer, to allow getting the attribute by value if needed:

function getElementsByAttributeValue(attribute, value){
  var matchingElements = [];
  var allElements = document.getElementsByTagName('*');
  for (var i = 0, n = allElements.length; i < n; i++) {
    if (allElements[i].getAttribute(attribute) !== null) {
      if (!value || allElements[i].getAttribute(attribute) == value)
        matchingElements.push(allElements[i]);
    }
  }
  return matchingElements;
}

Don't use in Browser

In the browser, use document.querySelect('[attribute-name]').

But if you're unit testing and your mocked dom has a flakey querySelector implementation, this will do the trick.

This is @kevinfahy's answer, just trimmed down to be a bit with ES6 fat arrow functions and by converting the HtmlCollection into an array at the cost of readability perhaps.

So it'll only work with an ES6 transpiler. Also, I'm not sure how performant it'll be with a lot of elements.

function getElementsWithAttribute(attribute) {
  return [].slice.call(document.getElementsByTagName('*'))
    .filter(elem => elem.getAttribute(attribute) !== null);
}

And here's a variant that will get an attribute with a specific value

function getElementsWithAttributeValue(attribute, value) {
  return [].slice.call(document.getElementsByTagName('*'))
    .filter(elem => elem.getAttribute(attribute) === value);
}

참고URL : https://stackoverflow.com/questions/9496427/get-elements-by-attribute-when-queryselectorall-is-not-available-without-using-l

반응형