5

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.

Gajus
  • 69,002
  • 70
  • 275
  • 438
  • 2
    Possible duplicate of [Find HTML based on partial attribute](http://stackoverflow.com/questions/12199008/find-html-based-on-partial-attribute) – Ivanka Todorova Mar 16 '16 at 13:25
  • 1
    @IvankaTodorova that question is entirely [tag:jquery] focused. – Gajus Mar 16 '16 at 13:27
  • This is already answered here: http://stackoverflow.com/a/16791596/4523369 – Cihan Bebek Mar 16 '16 at 13:35
  • @Keksike Looking for a partial attribute value (your link) is not the same as looking for a partial attribute name (the problem of this question) – Andreas Mar 16 '16 at 13:39
  • There is no *attribute-name-starts-with*-selector-syntax, which you probably already know. Thus you need code to find those elements *by hand*. So the question is, what have you tried and where are you stuck? – Yoshi Mar 16 '16 at 13:47
  • @Yoshi I was only half confident that there is no way using DOM API to match elements that have pattern matching attributes. The solution to this issue is to iterate through all (or a sub-set) of DOM nodes and match each attribute. – Gajus Mar 16 '16 at 13:50
  • `*` is not a wildcard or regex. It means "includes" in DOM selector. And that's for values not the attribute name. `[data-foo-bar-*]` is incorrect syntax. `[data-foo-bar-*="some-value"]` is correct but will not give you what you want. – Onur Yıldırım Mar 16 '16 at 13:53

1 Answers1

1

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/

Ivanka Todorova
  • 9,964
  • 16
  • 66
  • 103