Search code examples
regexwildcardselectors-api

document.querySelectorAll('a[id="*"]'); and wildcard or regex?


Suppose a HTML document in which there are some internal anchor / bookmarks and other html generic content:

<a id='alfa'></a>
  other HTML content
<a id='beta'></a>
  other HTML content
<a id='gamma'></a>
  other HTML content
<a id='delta'></a>
  other HTML content
<a id='omega'></a>
  other HTML content
...
  other HTML content
<a id='etha'></a>

other HTML content: means anything else even other <a href='something'>, without any id set.

What I want is a cross (recent) browser solution to get all anchors with an id set but not those without any id.

But what I want is, if it is possibile, in pure js, to select in just one js command, all anchors that have their id attribute set to any generic valute.

I already know, there is the possibility to get them all, then with a for loop extract those I need, but this is not optimal solution. I also know https://stackoverflow.com/a/8714421/6508528 to get elements that start, end or contain some ids part. But what if I don't know any part/sub-string of the id?

I don't know may be something like:

var allAnchors = document.querySelectorAll('a[id="*"]');

that prevents the need to reprocess the array allAnchors after getting it.


Solution

  • This grabs all anchor elements with an id attr. set:

    document.querySelectorAll('a[id]');
    

    This grabs all the anchor elements with no id:

    document.querySelectorAll('a:not([id])');