Can I use a regular expression in querySelectorAll?

后端 未结 2 1449
情话喂你
情话喂你 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
    
    
    
    

    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(/(?
    
    
    
    

    I put it in a nice object layout for you.

提交回复
热议问题