Tuesday, March 27, 2018

Protractor find parent element

Leave a Comment
<label class="radio inline check">              <input class="input ng-new ng-valid" name="BookType" required="" type="radio">              <!---->              <!---->             Fiction </label>  <label class="radio inline check">                 <input class="input ng-new ng-valid" name="BookType" required="" type="radio">              <!---->              <!---->             NonFiction </label>  <label class="radio inline check">              <input class="input ng-new ng-valid" name="BookTypeReal" required="" type="radio">              <!---->              <!---->             Fiction </label>  <label class="radio inline check">                 <input class="input ng-new ng-valid" name="BookTypeReal" required="" type="radio">              <!---->              <!---->             Fantasy </label> 

http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.filter

If I use

element.all(locator).filter(filterFn)  

the text returned is empty.

How can I go to parent element <label> to get the text?

label[class="radio inline check"]  

returns 60 elements where more than one getText will return same text so it won't be unique.

input[name="BookType"]  

returns two elements where each element is unique.

5 Answers

Answers 1

To click on the <input> tag whose <label> has text as Fiction and <input> tag has name as BookType you can use the following xpath :

"//label[@class='radio inline check' and contains(normalize-space(), 'Fiction')]/input[@class='input ng-new ng-valid' and @name='BookType']" 

Answers 2

If you need to click a radio button with @type="BookType" and parent label with text "Fiction", you can try below code:

element(By.xpath("//label[.='Fiction']/input[@name='BookType']")).click(); 

Answers 3

You have two options to do it:

  1. To get the parent element, as you mentioned. For this you can use xpath's ancestor for it like this:

    .//*[@name='BookType']/ancestor::label

  2. To get the text as the sibling of the element with @name='BookType':

    .//*[@name='BookType']/following-sibling::text()[normalize-space()]

Answers 4

In Xpath if you want parent of input you can use //input[name="BookType"]/..

Answers 5

i have framed this based on available details over the net. Please give a try.

element.all(by.css('.radio inline check')).filter(function(elem){         return elem.element(by.xpath("//*[text()[contains(.,'Fiction')]]")).getText()          }).then(function(filteredElements){         filteredElements.first().element(by.css('input[name=BookType]')).click();         }); 

Note: You may have some format issue in this.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment