keylogger
keylogger

Reputation: 872

How can I select the same children across different parents?

I have this HTML code

  <select  id="from">
    child  
      child
        child 
          <div class="dropdownDiv">
            <ul>
              <li class=""><a href="#"  text="John" value="Jo"> John </a></li>
              <li class=""><a href="#"  text="Mary" value="Ma"> Mary </a></li>
              <li class=""><a href="#"  text="Kevin" value="Ke"> Kevin </a></li>
              <li class=""><a href="#"  text="Sandra" value="Sa"> Sandra </a></li>
              <li class=""><a href="#"  text="Claire" value="Cl"> Claire </a></li>
          </ul>
       </div>
   </select>


   <select  id="to">
      child  
        child
          child 
            <div class="dropdownDiv">
              <ul>
                <li class=""><a href="#"  text="John" value="Jo"> John </a></li>
                <li class=""><a href="#"  text="Mary" value="Ma"> Mary </a></li>
                <li class=""><a href="#"  text="Kevin" value="Ke"> Kevin </a></li>
                <li class=""><a href="#"  text="Sandra" value="Sa"> Sandra </a></li>
                <li class=""><a href="#"  text="Claire" value="Cl"> Claire </a></li>
          </ul>
       </div>
   </select>
     

Using CSS_Selector in Java Selenium,

  1. how can I click Sandra from parent id="from" and
  2. how can I click Sandra from parent id="to" ?

Using Xpath, I could simply say

  1. driver.findElement(By.xpath("(//a[@value='Sa'])[1]")).click();
  2. driver.findElement(By.xpath("(//a[@value='Sa'])[2]")).click()

How can I do the same thing using CSS selectors?

Upvotes: 0

Views: 68

Answers (1)

Onel Harrison
Onel Harrison

Reputation: 1334

Your HTML needs to be corrected because div and ul aren't valid children of <select>. The valid children of <select> are <option> and <optgroup>.

<select  id="from">
    <option value="Jo">John</option>
    <option value="Ma">Mary</option>
    <option value="Ke">Kevin</option>
    <option value="Sa">Sandra</option>
    <option value="Cl">Claire</option>
</select>

<select  id="to">
    <option value="Jo">John</option>
    <option value="Ma">Mary</option>
    <option value="Ke">Kevin</option>
    <option value="Sa">Sandra</option>
    <option value="Cl">Claire</option>
</select>

Selenium

I recommend that you take a look at the Java documentation for Selenium.

With the corrected HTML, you are able to use driver.findElement(By.cssSelector("selector here")) to solve your problem. The documentation for that is here.

Here's an example for clicking Sandra with parent id="from".

driver.findElement(By.cssSelector("#from")).click(); // to show the drop down
driver.findElement(By.cssSelector("#from option[value=Sa]")).click();

You can modify the code above to work for the parent id="to" as well.

Upvotes: 2

Related Questions