Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/446.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在不使用库的情况下querySelectorAll不可用时按属性获取元素?_Javascript_Dom - Fatal编程技术网

Javascript 在不使用库的情况下querySelectorAll不可用时按属性获取元素?

Javascript 在不使用库的情况下querySelectorAll不可用时按属性获取元素?,javascript,dom,Javascript,Dom,它在哪里 我需要一个至少在IE7中工作的本机解决方案。我不关心IE6。您可以编写一个运行getElementsByTagName(“*”)的函数,并仅返回具有“data foo”属性的元素: document.querySelectorAll('[data-foo]') 我玩了一会儿,最终得到了这个粗糙的解决方案: getAllElementsWithAttribute('data-foo'); 用法非常简单,即使在IE8中也可以使用: function getElementsByAttri

它在哪里


我需要一个至少在IE7中工作的本机解决方案。我不关心IE6。

您可以编写一个运行getElementsByTagName(“*”)的函数,并仅返回具有“data foo”属性的元素:

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

我玩了一会儿,最终得到了这个粗糙的解决方案:

getAllElementsWithAttribute('data-foo');
用法非常简单,即使在IE8中也可以使用:

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;
}

但是我建议使用
querySelector
/
All
来实现这一点(要支持较旧的浏览器,请使用a):

使用


按属性查找元素。现在所有相关浏览器(甚至IE8)都支持它:

试试这个-我稍微改变了上面的答案:

//find all elements with "someAttr" attribute
document.querySelectorAll('[someAttr]') 
这也行得通:

getAttributes('data-foo');
因此:

不在浏览器中使用 在浏览器中,使用
document.querySelect(“[attribute name]”)

但是,如果您正在进行单元测试,并且您的模拟dom有一个鳞片状的querySelector实现,那么这样就可以了

这是@kevinfahy的答案,只是通过ES6 fat arrow函数进行了一些精简,并以可读性为代价将HtmlCollection转换为数组

因此,它只适用于ES6 transpiler。另外,我不确定它在很多元素下的性能如何

document.querySelector([data-foo="bar"]);
这里有一个变量,它将获得一个具有特定值的属性

function getElementsWithAttribute(attribute) {
  return [].slice.call(document.getElementsByTagName('*'))
    .filter(elem => elem.getAttribute(attribute) !== null);
}
试试这个,它管用

document.querySelector('[attribute=“value”]'))

例如:

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

对@kevinfahy的稍作修改,以允许在需要时按值获取属性:

document.querySelector('[role="button"]')
函数getElementsByAttributeValue(属性,值){ var matchingElements=[]; var-allegements=document.getElementsByTagName('*'); 对于(var i=0,n=allegements.length;i使用
!=null
是一种理想的方法(比我上面的评论更好),因为在旧IE中,getAttribute可以返回一个
类型为
'number'
的值,为什么使用
文档。getElementsByTagName('*')
而不是
文档。all
?为什么不使用
hasAttribute
而不是
getAttribute()!==null
,因为您只想检查是否存在,而不是它的值?请查看javascript选择器库nice是的,我需要做的唯一选择是数据属性,所以我试图找到最简单的方法来修补它,而不需要像Sizzle这样的整个选择器引擎。但从源头上看,这是一个很好的观点。顺便说一句,另一个很棒的选择引擎是@ryanve,谢谢,我会看一看:)我使用的工作解决方案是在名为'queryAttr'的方法中,Lol,你的问题就是我的答案。这是另一个问题。在什么情况下,
querySelectorAll
不可用<代码>备注-我不在乎所有IE
你改变了什么,为什么?是的,querySelectorAll+1。快速的jsperf测试表明,它比公认的答案快得多。。。不幸的是,它与IE 7不兼容:(在实际的querySelector中缺少单引号。应该是:
document.querySelector('[data foo=“bar”]);
当问题明确要求:“我需要一个至少在IE7中工作的本机解决方案”时,它怎么会有这么多的向上投票第二,该链接指出,支持从IE11开始,即使它实际上从IE8开始-也许这应该被替换为,所以它实际上支持答案…?所有向上投票的原因,也是我给出答案的原因,是这个问题非常古老,所以当你搜索如何查找DOM元素时,你会发现这个问题已经存在在搜索结果中排名很高,因为这正是人们想要的。有用性>历史准确性。其次,链接仍然可以正常工作,只是caniuse.com隐藏了旧浏览器,如果你切换到“相对使用率”,你仍然可以看到旧浏览器。工作完美。快速简单
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;
};
getAttributes('data-foo');
document.querySelector([attribute="value"]);
document.querySelector([data-foo="bar"]);
function getElementsWithAttribute(attribute) {
  return [].slice.call(document.getElementsByTagName('*'))
    .filter(elem => elem.getAttribute(attribute) !== null);
}
function getElementsWithAttributeValue(attribute, value) {
  return [].slice.call(document.getElementsByTagName('*'))
    .filter(elem => elem.getAttribute(attribute) === value);
}
document.querySelector('[role="button"]')
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;
}