Class: Watir::ElementCollection

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/watir-webdriver/element_collection.rb

Overview

Base class for element collections.

Instance Method Summary collapse

Constructor Details

#initialize(parent, selector) ⇒ ElementCollection



11
12
13
14
# File 'lib/watir-webdriver/element_collection.rb', line 11

def initialize(parent, selector)
  @parent   = parent
  @selector = selector
end

Instance Method Details

#[](idx) ⇒ Watir::Element

Get the element at the given index.

Also note that because of Watir's lazy loading, this will return an Element instance even if the index is out of bounds.



53
54
55
# File 'lib/watir-webdriver/element_collection.rb', line 53

def [](idx)
  to_a[idx] || element_class.new(@parent, @selector.merge(:index => idx))
end

#each {|element| ... } ⇒ Object

Yields each element in collection.

Examples:

divs = browser.divs(:class => 'kls')
divs.each do |div|
  puts div.text
end

Yield Parameters:

  • element (Watir::Element)

    Iterate through the elements in this collection.



28
29
30
# File 'lib/watir-webdriver/element_collection.rb', line 28

def each(&blk)
  to_a.each(&blk)
end

#firstWatir::Element

First element of this collection



63
64
65
# File 'lib/watir-webdriver/element_collection.rb', line 63

def first
  self[0]
end

#lastWatir::Element

Last element of the collection



73
74
75
# File 'lib/watir-webdriver/element_collection.rb', line 73

def last
  self[-1]
end

#lengthFixnum Also known as: size

Returns number of elements in collection.



38
39
40
# File 'lib/watir-webdriver/element_collection.rb', line 38

def length
  elements.length
end

#to_aArray<Watir::Element>

This collection as an Array.



83
84
85
86
# File 'lib/watir-webdriver/element_collection.rb', line 83

def to_a
  # TODO: optimize - lazy element_class instance?
  @to_a ||= elements.map { |e| element_class.new(@parent, :element => e) }
end