Can I use a regular expression in querySelectorAll?

后端 未结 2 1428
情话喂你
情话喂你 2020-11-30 03:15

On a page I\'m doing I will be ending up with custom link elements like this:



        
相关标签:
2条回答
  • 2020-11-30 03:21

    I know this is 7 years old, but this is how you do it (for attribute values):

    function DOMRegex(regex) {
        let output = [];
        for (let i of document.querySelectorAll('*')) {
            if (regex.test(i.type)) { // or whatever attribute you want to search
                output.push(i);
            }
        }
        return output;
    }
    console.log(DOMRegex(/^service\//)); // your regex here
    <link rel="multiply" type="service/math" src="path/to/service">
    <link rel="substract" type="service/math" src="path/to/service">
    <link rel="test" type="notservice/math" src="path/to/notservice">
    <div id="some-other-node"></div>

    To search all element attributes, you can use this:

    function DOMRegex(regex) {
        let output = [];
        for (let i of document.querySelectorAll('*')) {
            for (let j of i.attributes) {
                if (regex.test(j.value)) {
                    output.push({
                        'element': i,
                        'attribute name': j.name,
                        'attribute value': j.value
                    });
                }
            }
        }
        return output;
    }
    console.log(DOMRegex(/(?<!t)service/)); // your regex here
    <link rel="multiply" type="service/math" src="path/to/service">
    <link rel="substract" type="service/math" src="path/to/service">
    <link rel="test" type="notservice/math" src="path/to/notservice">
    <div id="some-other-node"></div>

    I put it in a nice object layout for you.

    0 讨论(0)
  • 2020-11-30 03:29

    You can't really use a regular expression in a selector but CSS selectors are powerful enough for your need with a "starts with" syntax inspired by regexes.

    You can use a substring matching attribute selectors : link[type^=service]

    Reads "Nodes of type link with an attribute type starting with "service"

    From the formal specification:

    [att^=val]

    Represents an element with the att attribute whose value begins with the prefix "val". If "val" is the empty string then the selector does not represent anything.

    Working JSFiddle

    0 讨论(0)
提交回复
热议问题