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.
@T.J.Crowder's answer is right in everything.
But IMK a faster way to implement a custom
querySelector
method should definitely be done with a TreeWalker.Here is a simple (probably not perfect) implementation of what you are after, using the
ng-
filtering proposed by T.J:PS: any upvote on this answer should also be rewarded to T.J's one too.
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.
If you know the list you'll be processing will be small, you can do it with a naive version query-then-filter; if you think it may be larger, a DOM walker solution (see below) would probably be better.
The naive query-then-filter (ES2015 syntax):
ES5 version:
Walker solution (ES2015+):
ES5:
For all of the above, note that
String#startsWith
may need a shim prior to ES2015.