In following html
<p>
<strong>Name:</strong>
12121
</p>
How can I access the "12121" text using Watir?
In following html
<p>
<strong>Name:</strong>
12121
</p>
How can I access the "12121" text using Watir?
browser.p.text returns "Name: 12121" and browser.p.strong.text returns "Name:".
> browser.p.text
=> "Name: 12121"
> browser.p.strong.text
=> "Name:"
To get 12121 one (or more) of String methods could be used, for example String#split and then String#lstrip.
> long = b.p.text
=> "Name: 12121"
> short = b.p.strong.text
=> "Name:"
> long.split(short)
=> ["", " 12121"]
> long.split(short)[1]
=> " 12121"
> long.split(short)[1].lstrip
=> "12121"
While I think that parsing the paragraph elements text is the easiest, if you really just want to get the text node, you could use javascript.
If you know that the text will always be the last part of the paragraph, you can do:
browser.execute_script("return arguments[0].lastChild.nodeValue", browser.p)
#=> "12121"
If the structure can change and you want all text of the paragraph element, without the children element's text, you can generalize it:
get_text_node_script = <<-SCRIPT
var nodes = arguments[0].childNodes;
var result = "";
for(var i = 0; i < nodes.length; i++) {
if(nodes[i].nodeType == Node.TEXT_NODE) {
result += nodes[i].nodeValue;
}
}
return result
SCRIPT
browser.execute_script(get_text_node_script, browser.p)
#=> "12121"