Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find an element that has an attribute matching a pattern

Tags:

javascript

dom

How to find all elements that have attributes that match pattern data-foo-bar-*, e.g.

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

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

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

like image 505
Gajus Avatar asked Nov 08 '22 18:11

Gajus


1 Answers

Maybe iterating through all DOM elements and looking for this specific attribute might not be the best approach, but here's my try:

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/

like image 125
Ivanka Todorova Avatar answered Nov 15 '22 11:11

Ivanka Todorova