Jo Colina Jo Colina - 4 months ago 15
HTML Question

querySelector, get elements whose attribute begins with given string

I'm looking for a way to find all elements that contain an attribute that begins witha a given string. For example:

document.querySelectorAll('[ng-*]')
would return all elements with Angular directives (
ng-click
,
ng-show
,
ng-hide
...).

But the wildcard does not seem to work.

Any ideas? I could implement my own, but it wouldn't be as effective.

Answer

There's no CSS selector that lets you do wildcards on the name of an attribute, just on the value, which obviously isn't want you want.

Unfortunately, you'll have to do the work manually, something like this (ES2015 syntax):

let elements = Array.prototype.filter.call(
  document.querySelectorAll("*"), // Best if you can use *something* here
                                  // to keep the list to a minimum
  element => Array.prototype.some.call(
    element.attributes,
    attr => attr.nodeName.startsWith("ng-")
  )
);
console.log(elements);
<div></div>
<div ng-bar></div>
<div></div>
<div ng-foo></div>
<div></div>

ES5 syntax:

var elements = Array.prototype.filter.call(
  document.querySelectorAll("*"), // Best if you can use *something* here
                                  // to keep the list to a minimum
  function(element) {
    return Array.prototype.some.call(
      element.attributes,
      function(attr) {
        return attr.nodeName.startsWith("ng-");
      }
    );
  }
);
console.log(elements);
<div></div>
<div ng-bar></div>
<div></div>
<div ng-foo></div>
<div></div>

Comments