title: WebDriver (Java) - Exclude elements under a Table when using driver.findElements()
body: <p>Using WebDriver, I am writing a code to find all elements of a specific kind on a given area of a page (which can also be the entire page itself). </p>
  
  <p>Let's say my page is like this</p>
  
  <pre><code>&lt;div id='mydiv'&gt;
      &lt;a href='#' id='mylink_1'&gt;Link 01&lt;/a&gt;
      &lt;a href='#' id='mylink_2'&gt;Link 02&lt;/a&gt;
      &lt;span&gt;Enter your name&lt;/span&gt;
      &lt;input type='text' id='txtName' value=''/&gt;
      &lt;div id='mytable'&gt;
          &lt;table id='mytableelement'&gt;
              &lt;tr&gt;
                  &lt;td&gt;&lt;a href='#' id='table_link_1'&gt;Table Link 1&lt;/a&gt;&lt;/td&gt;
                  &lt;td&gt;&lt;input type='text' id='table_text_1' value=''/&gt;&lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td&gt;&lt;a href='#' id='table_link_2'&gt;Table Link 2&lt;/a&gt;&lt;/td&gt;
                  &lt;td&gt;&lt;input type='text' id='table_text_2' value=''/&gt;&lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td&gt;&lt;a href='#' id='table_link_3'&gt;Table Link 3&lt;/a&gt;&lt;/td&gt;
                  &lt;td&gt;&lt;input type='text' id='table_text_3' value=''/&gt;&lt;/td&gt;
              &lt;/tr&gt;
          &lt;/table&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>Now, my requirement is to, say, get all the links under the div 'mydiv'.</p>
  
  <p>So, I've written a code like this</p>
  
  <pre><code>WebElement myDiv = driver.findElement(By.id("mydiv"));
  List&lt;WebElement&gt; links = myDiv.findElements(By.tagName("a"));
  </code></pre>
  
  <p>This will return me <b>All</b> links under 'mydiv', which is fine. However, I want to exclude the links that occur under the <b>table</b> tag, that is, links with ID 'table_link_1', 'table_link_2','table_link_3'.</p>
  
  <p>In order to achieve this, I did the following</p>
  
  <pre><code>ArrayList&lt;WebElement&gt; finalLinks =  new ArrayList&lt;WebElement&gt;();
  WebElement myDiv = driver.findElement(By.id("mydiv"));
  List&lt;WebElement&gt; links = myDiv.findElements(By.tagName("a"));
  for(WebElelemnt link:links){
    try{
        WebElement containingtable = link.findElement(By.xpath("ancestor::table[1]"));
        System.out.println("Element occurs inside a table. So, skip it");
    }
    catch(Exception e){
        finalLinks.add(link);
    }
  }
  </code></pre>
  
  <p>This seems to work too, but the only problem is, if the table contains 1000 rows, then it loops for 1000 links, only to skip them. This obviously hits performance. </p>
  
  <p>IS there a faster way of skipping the links under the table?</p>
  
  <p><b>Note:</b> The table here is only an example. I may want to skip a specific div or a set of divs which are nested too.</p>
  
  <p>Can there be a generic way of doing this?</p>
  
  <p>Thank you,
  Sriram</p>