-2

I'm struggling to get proper css (or any pother) locator for my checkbox. There are two on the page with same attributes by different text, I don't know how to build working selector. I want to avoid using index. I want to select them by 'Name1' and 'Name2' Here are the attributes:

<label>
<input class="some class name" name="checkOptions" type="checkbox">Name1
</label>

<label>
<input class="some class name" name="checkOptions" type="checkbox">Name2
</label>
jacob1989
  • 15
  • 3
  • 1
    'by different names' --> They have the same name? – 0stone0 Apr 26 '21 at 09:26
  • sorry, I meant 'displayed text', not the attribute 'name' (corrected) – jacob1989 Apr 26 '21 at 09:27
  • Maybe something like this: "(//input[text()='Name1'])" – Andreas Apr 26 '21 at 09:30
  • Does this answer your question? [Is there a CSS selector for elements containing certain text?](https://stackoverflow.com/questions/1520429/is-there-a-css-selector-for-elements-containing-certain-text) – 0stone0 Apr 26 '21 at 09:30
  • If you could have used script it could be `[...document.querySelectorAll("label")] .filter(label => label.textContent.trim() === "Name2")[0] .querySelector("input").checked = true` – mplungjan Apr 26 '21 at 09:31
  • BTW: Please consider reading: [Does a name attribute have to be unique in a HTML document?](https://stackoverflow.com/questions/5518458/does-a-name-attribute-have-to-be-unique-in-a-html-document). – 0stone0 Apr 26 '21 at 09:32

2 Answers2

1

If the only uniqueness of the elements is their texts you have to locate them according to that texts.
Try this xpath: //input[contains(text(),'Name1')] for the first and //input[contains(text(),'Name2')] for the second element.
In case you need to add more uniqueness you can add the class name or any other attribute like following:
//input[@class='some class name' and contains(text(),'Name1')] and
//input[@class='some class name' and contains(text(),'Name2')]

Prophet
  • 32,350
  • 22
  • 54
  • 79
  • this one doesn't return any locator, NoSuchElementException – jacob1989 Apr 26 '21 at 10:20
  • What `xpath` did you try? Are you sure 'Name1' is text and not a value? Did you give enough delay before searching for the element? – Prophet Apr 26 '21 at 10:44
  • Also, I hope you are using a correct `By` i.e. `driver.findElements(By.xpath(//input[contains(text(),'Name1')]));` – Prophet Apr 26 '21 at 11:18
0

In your examples, the text is inside label (...and outside input...).

Well, possible alternative is use css ":contains" selector

  $("label:contains('Name1')").css('background-color', 'red');

For get input:

  $("label:contains('Name1') > input")

Consider this native function is case sensitive. Alternative can create custom function:

$.expr[':'].containsCaseIns = function(a, i, m) {
  return $(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};

$("label:containsCaseIns('Name1') > input")
Simone S.
  • 1,756
  • 17
  • 18