Feroz
Feroz

Reputation: 61

How to access the sub text having no attributes using Watir

In following html

<p>
<strong>Name:</strong>
12121
</p>

How can I access the "12121" text using Watir?

Upvotes: 3

Views: 428

Answers (3)

Justin Ko
Justin Ko

Reputation: 46836

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"

Upvotes: 1

user3791
user3791

Reputation: 391

To get subtext 12121 use Regular expressions.
gsub performs a search-and-replace operation. It will search for all non-digit characters(/\D/) and replace with the given string. In this case we are not giving any string to replace.


=browser.p.text.gsub(/\D/, "")
=> "12121"

Upvotes: 3

Željko Filipin
Željko Filipin

Reputation: 57262

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"

Upvotes: 1

Related Questions