Query Selector: How to Or Selection

Query Selector: How to Or Selection

This is probably an odd topic, however I was recently asked how could one select between 2 possible elements on a browser using Protractor. If you are unfamiliar with Protractor it is a testing tool for AngularJS applications. To start lets show a code example of what we are looking at.

<html>
<body>
  <div id='ex1'>
    <!-- some code here -->
  </div>
  <div id='ex2'>
    <!-- some code here -->
  </div>
</body>
</html>

Notice from the code that we have 2 divs with id’s ex1 and ex2. Now depending on the code you ex1 or ex2 can be hidden. Lets say hypothetically they both do the exact same thing and you just want to click which ever one happens to be available. At the same time you also don’t want to add expensive checks for isPresent or waits. To get around this you can do the following with the by.css query selector.

  $('[id="ex1"], [id="ex2"]')

Did you know that this same query selector will also work within JQuery, and the DevTools Console on your browser? Give it a try on this page.

  1. Goto your DevTools Console in Browser
  2. Type: $('[id="ex1"], [id="ex2"]')
  3. Hit Enter