Xpath: how to select an option based on its text not value property?

29,293

Solution 1

To select by text value you can use text() function. And normalize spaces is required, because they are not removed by default. Here is an example:

select/option[normalize-space(text())="Grass"]

@value - value of "value" attribute

@val - value of "val" attribute

normalize-space() - function returns the argument string with whitespace normalized by stripping leading and trailing whitespace and replacing sequences of whitespace characters by a single space

Solution 2

Well, if whitespace isn't an issue:

/select/option[.='Grass']

I'd need to check re whitespace, though. You could always normalize:

/select/option[normalize-space(.)='Grass']
Share:
29,293

Related videos on Youtube

h34y
Author by

h34y

Updated on July 09, 2022

Comments

  • h34y
    h34y almost 2 years

    consider both types:

    <select name="garden">
        <option>Flowers</option>
        <option selected="selected">Shrubs</option>
        <option>Trees</option>
        <option selected="selected">Bushes</option>
        <option>Grass</option>
        <option>Dirt</option>
    </select>
    

    Is @val for actually indicating the value="" attribute ?

    Is @value for indicating the innerText value ?

    for example what happens if <option> doesn't contain any value="" property. how would you select it then ?

    select/option[@value = "Grass"] 
    

    Does Xpath automatically ignore white spaces for the case above? Should it be trimmed?

    EDIT:

    for selecting multiple options would this suffice ?

    select/option[normalize-space(text())="Grass" or normalize-space(text())="Trees"]
    
  • h34y
    h34y over 14 years
    for selecting multiple options would this suffice ? select/option[normalize-space(text())="Grass" or normalize-space(text())="Trees"]
  • h34y
    h34y over 14 years
    for selecting multiple options would this suffice ? select/option[normalize-space(.)="Grass" or normalize-space(.)="Trees"]
  • Pavel Minaev
    Pavel Minaev over 14 years
    It's okay, except that text() is not a function. It's a node test. And Marc's answer is both shorter, and more idiomatic for XPath.
  • Ivan Nevostruev
    Ivan Nevostruev over 14 years
    BTW, how text() should be called (if it's not a function)?
  • Tatarin
    Tatarin almost 9 years
    This seems to be case-sensitive. Is there a way to make this otherwise?
  • Marc Gravell
    Marc Gravell almost 9 years