How to get the number of elements having same attribute in HTML in Watir?
Asked Answered
S

1

8

I have a HTML document which contains elements having the same class name. I could just do an iteration over all the elements in a page and store with elements with a class name in a list. Is there a better way in Watir to get a count of all the HTML elements having the same class name? This question Count of Elements with same attribute in XML kind of addresses the issue, but I had two queries related to that

  1. What if the HTML document is not a strict XHTML document?
  2. What happens if different types of HTML elements have the same class?

Sample HTML files could be:

Elements of the same type having same class name

<input type="password" class="foo" /> 
<input type="text" class="foo" />

Elements of different types having same class name

<input type="password" class="foo" /> 
<span class="foo"></span>
<a href='1' class="foo">Text</a>

Thanks in advance, guys

Subversion answered 21/6, 2011 at 23:12 Comment(1)
added watir-webdriver and also ruby as this might be more of a ruby question than a watir question.Lysippus
A
22

If you are using watir-webdriver gem:

1)

HTML

<input type="password" class="foo" /> 
<input type="text" class="foo" />

Watir

browser.elements(:class => "foo").size
# => 2 

2)

HTML

<input type="password" class="foo" /> 
<span class="foo"></span>
<a href='1' class="foo">Text</a>

Watir

browser.elements(:class => "foo").size
# => 3 
Amato answered 22/6, 2011 at 7:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.