Javascript 不使用 jQuery 选择所有具有“data-”属性的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7084557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:46:53  来源:igfitidea点击:

Select all elements with "data-" attribute without using jQuery

javascripthtmldom

提问by DrANoel

Using only JavaScript, what is the most efficient way to select all DOM elements that have a certain data-attribute (let's say data-foo). The elements may be different tag elements.

仅使用 JavaScript,选择具有特定data-属性的所有 DOM 元素的最有效方法是什么(比方说data-foo)。元素可以是不同的标签元素。

<p data-foo="0"></p><br/><h6 data-foo="1"></h6>

回答by Joe

You can use querySelectorAll:

您可以使用querySelectorAll

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

回答by Joseph Marikle

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

will get you all elements with that attribute.

将为您提供具有该属性的所有元素。

document.querySelectorAll("[data-foo='1']")

will only get you ones with a value of 1.

只会得到值为 1 的值。

回答by shawndumas

Try it → here

试试→这里

    <!DOCTYPE html>
    <html>
        <head></head>
        <body>
            <p data-foo="0"></p>
            <h6 data-foo="1"></h6>
            <script>
                var a = document.querySelectorAll('[data-foo]');

                for (var i in a) if (a.hasOwnProperty(i)) {
                    alert(a[i].getAttribute('data-foo'));
                }
            </script>
        </body>
    </html>

回答by Heinrich Ulbricht

Hereis an interesting solution: it uses the browsers CSS engine to to add a dummy property to elements matching the selector and then evaluates the computed style to find matched elements:

是一个有趣的解决方案:它使用浏览器的 CSS 引擎向与选择器匹配的元素添加一个虚拟属性,然后评估计算出的样式以找到匹配的元素:

It does dynamically create a style rule [...] It then scans the whole document (using the much decried and IE-specific but very fast document.all) and gets the computed style for each of the elements. We then look for the foo property on the resulting object and check whether it evaluates as “bar”. For each element that matches, we add to an array.

它确实动态地创建了一个样式规则 [...] 然后它扫描整个文档(使用备受谴责和 IE 特定但非常快的 document.all)并获取每个元素的计算样式。然后我们在结果对象上查找 foo 属性并检查它是否评估为“bar”。对于匹配的每个元素,我们添加到一个数组中。

回答by Brian

var matches = new Array();

var allDom = document.getElementsByTagName("*");
for(var i =0; i < allDom.length; i++){
    var d = allDom[i];
    if(d["data-foo"] !== undefined) {
         matches.push(d);
    }
}

Not sure who dinged me with a -1, but here's the proof.

不知道是谁给了我 -1,但这是证据。

http://jsfiddle.net/D798K/2/

http://jsfiddle.net/D798K/2/

回答by Brian

While not as pretty as querySelectorAll(which has a litany of issues), here's a very flexible function that recurses the DOM and should work in most browsers (old and new). As long as the browser supports your condition (ie: data attributes), you should be able to retrieve the element.

虽然不像querySelectorAll(有很多问题)那么漂亮,但这里有一个非常灵活的函数,它可以递归 DOM,并且应该可以在大多数浏览器(新旧浏览器)中使用。只要浏览器支持您的条件(即:数据属性),您就应该能够检索该元素。

To the curious: Don't bother testing this vs. QSA on jsPerf. Browsers like Opera 11 will cache the query and skew the results.

好奇的人:不要费心在 jsPerf 上测试这个 vs. QSA。像 Opera 11 这样的浏览器会缓存查询并扭曲结果。

Code:

代码:

function recurseDOM(start, whitelist)
{
    /*
    *    @start:        Node    -    Specifies point of entry for recursion
    *    @whitelist:    Object  -    Specifies permitted nodeTypes to collect
    */

    var i = 0, 
    startIsNode = !!start && !!start.nodeType, 
    startHasChildNodes = !!start.childNodes && !!start.childNodes.length,
    nodes, node, nodeHasChildNodes;
    if(startIsNode && startHasChildNodes)
    {       
        nodes = start.childNodes;
        for(i;i<nodes.length;i++)
        {
            node = nodes[i];
            nodeHasChildNodes = !!node.childNodes && !!node.childNodes.length;
            if(!whitelist || whitelist[node.nodeType])
            {
                //condition here
                if(!!node.dataset && !!node.dataset.foo)
                {
                    //handle results here
                }
                if(nodeHasChildNodes)
                {
                    recurseDOM(node, whitelist);
                }
            }
            node = null;
            nodeHasChildNodes = null;
        }
    }
}

You can then initiate it with the following:

然后,您可以使用以下命令启动它:

recurseDOM(document.body, {"1": 1});for speed, or just recurseDOM(document.body);

recurseDOM(document.body, {"1": 1});为了速度,或者只是 recurseDOM(document.body);

Example with your specification: http://jsbin.com/unajot/1/edit

您的规范示例:http: //jsbin.com/unajot/1/edit

Example with differing specification: http://jsbin.com/unajot/2/edit

具有不同规格的示例:http: //jsbin.com/unajot/2/edit