Search code examples
javascripthtmlselectors-api

document.querySelectorAll() of multiple values


I have this code:

<a href="javascript:alert('something1')">Click</a>
<a href="javascript:prompt('something2')">Click</a>
<a href="javascript:alert('something3')">Click</a>
<a href="javascript:prompt('something4')">Click</a>

To get individual set element, I use document.querySelectorAll("a[href^='javascript:alert("); and document.querySelectorAll("a[href^='javascript:prompt");.

Now, how can use a generic document.querySelectorAll() to get all such <a href elements which contains alert, and prompt?

I tried this:

document.querySelectorAll("a[href^='javascript:prompt(,a[href^='javascript:alert(");

document.querySelectorAll("a[href^='javascript:prompt(","a[href^='javascript:alert(");

and so many. But it doesn't work, got "DOMException - not a valid selector" error.

Any help?


Solution

  • Your selector is not valid

    1. Missing closing quote of attribute value(').
    2. Missing ending of attribute selector ].
    3. Also use querySelectorAll to get NodeList, querySelector only return single element .

    console.log(
      document.querySelectorAll("a[href^='javascript:prompt('],a[href^='javascript:alert(']")
      //----------------------------------------------------^^---------------------------^^^
    );
    <a href="javascript:alert('something1')">Click</a>
    <a href="javascript:prompt('something2')">Click</a>
    <a href="javascript:alert('something3')">Click</a>
    <a href="javascript:prompt('something4')">Click</a>