Find an element that has an attribute matching the pattern.

How to find all elements that have attributes that match the data-foo-bar-* pattern, for example.

 <div data-foo-bar-id="" /> 

Using document.querySelectorAll with the foo-bar-* pattern gives an error:

Uncaught SyntaxError: Failed to execute 'querySelectorAll' in 'Document': '[data-foo-bar- *]' is not a valid selector.

+5
source share
1 answer

Iterating through all the DOM elements and finding this particular attribute may not be the best approach, but here's my attempt:

 function querySelectorPattern(regex, element) { var elements = document.getElementsByTagName(element), found, regexp = new RegExp(regex); for (var i = 0; i < elements.length; i++) { var attributes = elements[i].attributes; for (var k = 0; k < attributes.length; k++) { if(regexp.test(attributes[k].nodeName)) { console.log(elements[i]); } } } } 

And a quick demo: https://jsfiddle.net/1rsngvy8/

+1
source

Source: https://habr.com/ru/post/1245163/


All Articles