Class: Watir::Element

Inherits:
Object
  • Object
show all
Extended by:
AttributeHelper
Includes:
Container, EventuallyPresent, Exception
Defined in:
lib/watir-webdriver/elements/element.rb,
lib/watir-webdriver/extensions/select_text.rb

Overview

Base class for HTML elements.

Direct Known Subclasses

HTMLElement

Constant Summary

Constants included from Atoms

Atoms::ATOMS

Instance Method Summary collapse

Methods included from AttributeHelper

attribute, attribute_list, inherit_attributes_from, method, typed_attributes

Methods included from EventuallyPresent

#wait_until_present, #wait_while_present, #when_enabled, #when_present

Methods included from Container

#a, #abbr, #abbrs, #address, #addresses, #animate, #animate_motion, #animate_motions, #animate_transform, #animate_transforms, #animates, #area, #areas, #article, #articles, #as, #aside, #asides, #audio, #audios, #b, #base, #bases, #bdi, #bdis, #bdo, #bdos, #blockquote, #blockquotes, #body, #bodys, #br, #brs, #bs, #button, #buttons, #canvas, #canvases, #caption, #captions, #checkbox, #checkboxes, #circle, #circles, #cite, #cites, #code, #codes, #col, #colgroup, #colgroups, #cols, #cursor, #cursors, #data, #datalist, #datalists, #datas, #dd, #dds, #defs, #defss, #del, #dels, #desc, #descs, #details, #detailses, #dfn, #dfns, #dialog, #dialogs, #discard, #discards, #div, #divs, #dl, #dls, #dt, #dts, #element, #elements, #ellipse, #ellipses, #em, #embed, #embeds, #ems, #extract_selector, #field_set, #field_sets, #fieldset, #fieldsets, #figcaption, #figcaptions, #figure, #figures, #file_field, #file_fields, #font, #fonts, #footer, #footers, #foreign_object, #foreign_objects, #form, #forms, #frame, #frames, #frameset, #framesets, #g, #gs, #h1, #h1s, #h2, #h2s, #h3, #h3s, #h4, #h4s, #h5, #h5s, #h6, #h6s, #head, #header, #headers, #heads, #hgroup, #hgroups, #hidden, #hiddens, #hr, #hrs, #htmls, #i, #iframe, #iframes, #image, #images, #img, #imgs, #input, #inputs, #ins, #inses, #is, #kbd, #kbds, #keygen, #keygens, #label, #labels, #legend, #legends, #li, #line, #linear_gradient, #linear_gradients, #lines, #link, #links, #lis, #main, #mains, #map, #maps, #mark, #marker, #markers, #marks, #menu, #menuitem, #menuitems, #menus, #mesh_gradient, #mesh_gradients, #mesh_patch, #mesh_patches, #mesh_row, #mesh_rows, #meta, #metadata, #metadatas, #metas, #meter, #meters, #mpath, #mpaths, #nav, #navs, #noscript, #noscripts, #object, #objects, #ol, #ols, #optgroup, #optgroups, #option, #options, #output, #outputs, #p, #param, #params, #path, #paths, #pattern, #patterns, #polygon, #polygons, #polyline, #polylines, #pre, #pres, #progress, #progresses, #ps, #q, #qs, #radial_gradient, #radial_gradients, #radio, #radios, #rect, #rects, #rp, #rps, #rt, #rts, #rubies, #ruby, #s, #samp, #samps, #script, #scripts, #section, #sections, #select, #select_list, #select_lists, #selects, #set, #sets, #small, #smalls, #source, #sources, #span, #spans, #ss, #stop, #stops, #strong, #strongs, #styles, #sub, #subs, #summaries, #summary, #sup, #sups, #svg, #svgs, #switch, #switches, #symbol, #symbols, #table, #tables, #tbody, #tbodys, #td, #tds, #template, #templates, #text_field, #text_fields, #text_path, #text_paths, #textarea, #textareas, #tfoot, #tfoots, #th, #thead, #theads, #ths, #time, #times, #title, #titles, #tr, #track, #tracks, #trs, #tspan, #tspans, #u, #ul, #uls, #us, #use, #uses, #var, #vars, #video, #videos, #view, #views, #wbr, #wbrs

Methods included from Atoms

load

Methods included from XpathSupport

downcase, escape

Constructor Details

#initialize(parent, selector) ⇒ Element

Returns a new instance of Element.



25
26
27
28
29
30
31
32
33
# File 'lib/watir-webdriver/elements/element.rb', line 25

def initialize(parent, selector)
  @parent   = parent
  @selector = selector
  @element  = nil

  unless @selector.kind_of? Hash
    raise ArgumentError, "invalid argument: #{selector.inspect}"
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &blk) ⇒ Object (private)



632
633
634
635
636
637
638
639
# File 'lib/watir-webdriver/elements/element.rb', line 632

def method_missing(meth, *args, &blk)
  method = meth.to_s
  if method =~ Locators::Element::SelectorBuilder::WILDCARD_ATTRIBUTE
    attribute_value(method.tr('_', '-'), *args)
  else
    super
  end
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?

Returns true if two elements are equal.

Examples:

browser.text_field(name: "new_user_first_name") == browser.text_field(name: "new_user_first_name")
#=> true


65
66
67
# File 'lib/watir-webdriver/elements/element.rb', line 65

def ==(other)
  other.is_a?(self.class) && wd == other.wd
end

#attribute_value(attribute_name) ⇒ String?

Returns given attribute value of element.

Examples:

browser.a(id: "link_2").attribute_value "title"
#=> "link_title_2"

Parameters:

  • attribute_name (String)

Returns:

  • (String, nil)


270
271
272
273
# File 'lib/watir-webdriver/elements/element.rb', line 270

def attribute_value(attribute_name)
  assert_exists
  element_call { @element.attribute attribute_name }
end

#browserWatir::Browser

Returns browser.

Returns:



492
493
494
# File 'lib/watir-webdriver/elements/element.rb', line 492

def browser
  @parent.browser
end

#class_nameString

Returns value of className property.

Returns:

  • (String)

    value of className property



23
# File 'lib/watir-webdriver/elements/element.rb', line 23

attribute String, :class_name, :className

#click(*modifiers) ⇒ Object

Clicks the element, optionally while pressing the given modifier keys. Note that support for holding a modifier key is currently experimental, and may not work at all.

Examples:

Click an element

browser.element(name: "new_user_button").click

Click an element with shift key pressed

browser.element(name: "new_user_button").click(:shift)

Click an element with several modifier keys pressed

browser.element(name: "new_user_button").click(:shift, :control)

Parameters:

  • Modifier (:shift, :alt, :control, :command, :meta)

    key(s) to press while clicking.



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/watir-webdriver/elements/element.rb', line 113

def click(*modifiers)
  assert_exists
  assert_enabled

  element_call do
    if modifiers.any?
      assert_has_input_devices_for "click(#{modifiers.join ', '})"

      action = driver.action
      modifiers.each { |mod| action.key_down mod }
      action.click @element
      modifiers.each { |mod| action.key_up mod }

      action.perform
    else
      @element.click
    end
  end

  browser.after_hooks.run
end

#double_clickObject

Double clicks the element. Note that browser support may vary.

Examples:

browser.element(name: "new_user_button").double_click


143
144
145
146
147
148
149
# File 'lib/watir-webdriver/elements/element.rb', line 143

def double_click
  assert_exists
  assert_has_input_devices_for :double_click

  element_call { driver.action.double_click(@element).perform }
  browser.after_hooks.run
end

#drag_and_drop_by(right_by, down_by) ⇒ Object

Drag and drop this element by the given offsets. Note that browser support may vary.

Examples:

browser.div(id: "draggable").drag_and_drop_by 100, -200

Parameters:

  • right_by (Fixnum)
  • down_by (Fixnum)


215
216
217
218
219
220
221
222
223
224
# File 'lib/watir-webdriver/elements/element.rb', line 215

def drag_and_drop_by(right_by, down_by)
  assert_exists
  assert_has_input_devices_for :drag_and_drop_by

  element_call do
    driver.action.
           drag_and_drop_by(@element, right_by, down_by).
           perform
  end
end

#drag_and_drop_on(other) ⇒ Object

Drag and drop this element on to another element instance. Note that browser support may vary.

Examples:

a = browser.div(id: "draggable")
b = browser.div(id: "droppable")
a.drag_and_drop_on b


192
193
194
195
196
197
198
199
200
201
202
# File 'lib/watir-webdriver/elements/element.rb', line 192

def drag_and_drop_on(other)
  assert_is_element other
  assert_exists
  assert_has_input_devices_for :drag_and_drop_on

  element_call do
    driver.action.
           drag_and_drop(@element, other.wd).
           perform
  end
end

#driverObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



382
383
384
# File 'lib/watir-webdriver/elements/element.rb', line 382

def driver
  @parent.driver
end

#enabled?Boolean

Returns true if this element is present and enabled on the page.

Returns:

  • (Boolean)


412
413
414
415
# File 'lib/watir-webdriver/elements/element.rb', line 412

def enabled?
  assert_exists
  element_call { @element.enabled? }
end

#exists?Boolean Also known as: exist?

Returns true if element exists.

Returns:

  • (Boolean)


41
42
43
44
45
46
# File 'lib/watir-webdriver/elements/element.rb', line 41

def exists?
  assert_exists
  true
rescue UnknownObjectException, UnknownFrameException
  false
end

#fire_event(event_name) ⇒ Object

Simulates JavaScript events on element. Note that you may omit “on” from event name.

Examples:

browser.button(name: "new_user_button").fire_event :click
browser.button(name: "new_user_button").fire_event "mousemove"
browser.button(name: "new_user_button").fire_event "onmouseover"

Parameters:



357
358
359
360
361
362
# File 'lib/watir-webdriver/elements/element.rb', line 357

def fire_event(event_name)
  assert_exists
  event_name = event_name.to_s.sub(/^on/, '').downcase

  element_call { execute_atom :fireEvent, @element, event_name }
end

#flashObject

Flashes (change background color far a moment) element.

Examples:

browser.text_field(name: "new_user_first_name").flash


233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/watir-webdriver/elements/element.rb', line 233

def flash
  background_color = style("backgroundColor")
  element_color = driver.execute_script("arguments[0].style.backgroundColor", @element)

  10.times do |n|
    color = (n % 2 == 0) ? "red" : background_color
    driver.execute_script("arguments[0].style.backgroundColor = '#{color}'", @element)
  end

  driver.execute_script("arguments[0].style.backgroundColor = arguments[1]", @element, element_color)

  self
end

#focusObject

Focuses element. Note that Firefox queues focus events until the window actually has focus.



329
330
331
332
# File 'lib/watir-webdriver/elements/element.rb', line 329

def focus
  assert_exists
  element_call { driver.execute_script "return arguments[0].focus()", @element }
end

#focused?Boolean

Returns true if this element is focused.

Returns:

  • (Boolean)


340
341
342
343
# File 'lib/watir-webdriver/elements/element.rb', line 340

def focused?
  assert_exists
  element_call { @element == driver.switch_to.active_element }
end

#hashObject



70
71
72
# File 'lib/watir-webdriver/elements/element.rb', line 70

def hash
  @element ? @element.hash : super
end

#hoverObject

Moves the mouse to the middle of this element. Note that browser support may vary.

Examples:

browser.element(name: "new_user_button").hover


175
176
177
178
179
180
# File 'lib/watir-webdriver/elements/element.rb', line 175

def hover
  assert_exists
  assert_has_input_devices_for :hover

  element_call { driver.action.move_to(@element).perform }
end

#idString

temporarily add :id and :class_name manually since they’re no longer specified in the HTML spec.

TODO: use IDL from DOM core - dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html

Returns:

  • (String)

    value of id property

See Also:



22
# File 'lib/watir-webdriver/elements/element.rb', line 22

attribute String, :id, :id

#inner_htmlString

Returns inner HTML code of element.

Examples:

browser.div(id: 'foo').inner_html
#=> "<a href=\"#\">hello</a>"

Returns:

  • (String)


302
303
304
305
# File 'lib/watir-webdriver/elements/element.rb', line 302

def inner_html
  assert_exists
  element_call { execute_atom(:getInnerHtml, @element) }.strip
end

#inspectObject



49
50
51
52
53
54
55
# File 'lib/watir-webdriver/elements/element.rb', line 49

def inspect
  if @selector.key?(:element)
    '#<%s:0x%x located=%s selector=%s>' % [self.class, hash*2, !!@element, '{element: (webdriver element)}']
  else
    '#<%s:0x%x located=%s selector=%s>' % [self.class, hash*2, !!@element, selector_string]
  end
end

#outer_htmlString Also known as: html

Returns outer (inner + element itself) HTML code of element.

Examples:

browser.div(id: 'foo').outer_html
#=> "<div id=\"foo\"><a href=\"#\">hello</a></div>"

Returns:

  • (String)


285
286
287
288
# File 'lib/watir-webdriver/elements/element.rb', line 285

def outer_html
  assert_exists
  element_call { execute_atom(:getOuterHtml, @element) }.strip
end

#parentObject

Returns parent element of current element.



368
369
370
371
372
373
374
375
376
# File 'lib/watir-webdriver/elements/element.rb', line 368

def parent
  assert_exists

  e = element_call { execute_atom :getParentElement, @element }

  if e.kind_of?(Selenium::WebDriver::Element)
    Watir.element_class_for(e.tag_name.downcase).new(@parent, element: e)
  end
end

#present?Boolean

Returns true if the element exists and is visible on the page.

Returns:

  • (Boolean)

See Also:



424
425
426
427
428
429
430
# File 'lib/watir-webdriver/elements/element.rb', line 424

def present?
  exists? && visible?
rescue Selenium::WebDriver::Error::StaleElementReferenceError, UnknownObjectException
  # if the element disappears between the exists? and visible? calls,
  # consider it not present.
  false
end

#right_clickObject

Right clicks the element. Note that browser support may vary.

Examples:

browser.element(name: "new_user_button").right_click


159
160
161
162
163
164
165
# File 'lib/watir-webdriver/elements/element.rb', line 159

def right_click
  assert_exists
  assert_has_input_devices_for :right_click

  element_call { driver.action.context_click(@element).perform }
  browser.after_hooks.run
end

#select_text(str) ⇒ Object



5
6
7
8
# File 'lib/watir-webdriver/extensions/select_text.rb', line 5

def select_text(str)
  assert_exists
  execute_atom :selectText, @element, str
end

#send_keys(*args) ⇒ Object

Sends sequence of keystrokes to element.

Examples:

browser.text_field(name: "new_user_first_name").send_keys "Watir", :return

Parameters:



316
317
318
319
320
# File 'lib/watir-webdriver/elements/element.rb', line 316

def send_keys(*args)
  assert_exists
  assert_writable
  element_call { @element.send_keys(*args) }
end

#style(property = nil) ⇒ String

Returns given style property of this element.

Examples:

browser.button(value: "Delete").style           #=> "border: 4px solid red;"
browser.button(value: "Delete").style("border") #=> "4px solid rgb(255, 0, 0)"

Parameters:

  • property (String) (defaults to: nil)

Returns:

  • (String)


443
444
445
446
447
448
449
450
# File 'lib/watir-webdriver/elements/element.rb', line 443

def style(property = nil)
  if property
    assert_exists
    element_call { @element.style property }
  else
    attribute_value("style").to_s.strip
  end
end

#tag_nameString

Returns tag name of the element.

Returns:

  • (String)


91
92
93
94
# File 'lib/watir-webdriver/elements/element.rb', line 91

def tag_name
  assert_exists
  element_call { @element.tag_name.downcase }
end

#textString

Returns the text of the element.

Returns:

  • (String)


80
81
82
83
# File 'lib/watir-webdriver/elements/element.rb', line 80

def text
  assert_exists
  element_call { @element.text }
end

#to_subtypeObject

Cast this Element instance to a more specific subtype.

Examples:

browser.element(xpath: "//input[@type='submit']").to_subtype
#=> #<Watir::Button>


460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# File 'lib/watir-webdriver/elements/element.rb', line 460

def to_subtype
  elem = wd()
  tag_name = elem.tag_name.downcase

  klass = nil

  if tag_name == "input"
    klass = case elem.attribute(:type)
      when *Button::VALID_TYPES
        Button
      when 'checkbox'
        CheckBox
      when 'radio'
        Radio
      when 'file'
        FileField
      else
        TextField
      end
  else
    klass = Watir.element_class_for(tag_name)
  end

  klass.new(@parent, element: elem)
end

#valueString

Returns value of the element.

Returns:

  • (String)


253
254
255
256
257
# File 'lib/watir-webdriver/elements/element.rb', line 253

def value
  attribute_value('value') || ''
rescue Selenium::WebDriver::Error::InvalidElementStateError
  ''
end

#visible?Boolean

Returns true if this element is visible on the page.

Returns:

  • (Boolean)


401
402
403
404
# File 'lib/watir-webdriver/elements/element.rb', line 401

def visible?
  assert_exists
  element_call { @element.displayed? }
end

#wdObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



390
391
392
393
# File 'lib/watir-webdriver/elements/element.rb', line 390

def wd
  assert_exists
  @element
end