简体   繁体   中英

How to select a element if value/title contains a text

I have been trying to find out on how I can grab the element if a value contains "6 months". Here is few example and as we can see all of these values has the word 6 months and this is different scenarios of course so I don't want to click all of them but I gave example of different banktype that I need to click

<input type="button" aria-label="AMEX 6 months Extended Payment Plan" title="AMEX 6 months Extended Payment Plan" value="AMEX 6 months Extended Payment Plan" class="pm-button pp-content-btn pm-button-half">

<input type="button" aria-label="DBS IPP 6 months 0%" title="DBS IPP 6 months 0%" value="DBS IPP 6 months 0%" class="pm-button pp-content-btn pm-button-half">

<input type="button" aria-label="UOBSG IPP 6 months 0%" title="UOBSG IPP 6 months 0%" value="UOBSG IPP 6 months 0%" class="pm-button pp-content-btn pm-button-half">

and I wonder if its possible to click on a element if the value/title contains the word "6 months" inside it?

EDIT: Using protractor for testing

You can achieve this using xpaths with the contains function like so:

element(by.xpath('//input[contains(@title,"6 months")]');

The contains function is very useful for locating elements which contain certain text either in an attribute or in the node itself.

since you can't use the querySelectorAll, you might find this function helpful:

in case you don't depend on the element name:

FindByAttributeValue("Attribute-Name", "Attribute-Value");

or in case you do:

FindByAttributeValue("Attribute-Name", "Attribute-Value", "div");

and the full function implementation:

function FindByAttributeValue(attribute, value, element_type){
    element_type = element_type || "*";
    var All = document.getElementsByTagName(element_type);
    for (var i = 0; i < All.length; i++){
        if (All[i].getAttribute(attribute) == value){
            return All[i];
        }
    }
}

full answer came from HERE

That's exactly what by.cssContainingText does (partial text matcher in conjunction with css)

let elem = element(by.cssContainingText('[style]', '6 months'));

REVISION

1 way for doing what you need, but very inefficient... You may use .filter against elementArrayFinder several times until you narrow down the results to the element you need

But I'd look for the element you need by 2 parameters

let $elem = (bank, range) => element(by.xpath(`//input[contains(.,"${bank}") and contains(.,"${range}")]`));

Correct the xpath as needed. But essentially it looks for an input element that partially matches anything (attribute, text etc) with first parameter AND the second one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM