Identifying checkbox by neighboring label

For the life of me I cannot work out how to identify a checkbox based on its neighboring text label. Consider a page with checkboxes for each US state. The HTML contains multiple divisions which each contain a checkbox input and a label containing the US state. See attached code example screenshot.

There must be a way I can create a test object for each checkbox that references its association with a given state? I was wondering if xpath:neighbor can help (but can’t yet understand how to use this). I also tried to find a way of creating a hierarchy in the object repository, so I create each div and then UNDER it have a checkbox, but this doesn’t seem possible (I even tried creating an iframe test object with the same xpath as the DIV, and then dragged a checkbox input within it, but that didn’t work either).

I must be missing something as this has to be a common necessity.

hi,

try to copy Selector using chrome inspect option

Hi Timo, thanks for the suggestion. I had tried that, but again there’s no way that I can see where I can associate the checkbox with its neighboring text label.
Here’s what the parent DIV looks like as a selector:
#content > div > div > form > div:nth-child(4) > div > div > div:nth-child(1) > div:nth-child(2)
Here’s what the checkbox looks like:
#content > div > div > form > div:nth-child(4) > div > div > div:nth-child(1) > div:nth-child(2) > input
And here’s what the text label looks like:
#content > div > div > form > div:nth-child(4) > div > div > div:nth-child(1) > div:nth-child(2) > label

Thanks,
Graham

Graham,

If you use CSS selectors like that, you’re going to hate them the moment the developers change the page. Any time you see a long selector like that, be prepared for grief and sorrow…

If you want to show me more of the HTML (better, share a link to the page?) I’ll give you stronger, less brittle selectors.

And just so I’m clear, your intent is to click a specific radio based on the content of its associated label - correct? If so, you’ll want to use XPath (not CSS) and maybe get @Brandon_Hein involved (I don’t do XPath).

Thanks so much Russ. I have to be careful what I share, as the company I work for is Healthcare related and therefore subject to HIPAA, but I’ve attached a snippet of the HTML containing the problem area.
Yes you are quite right, I want some way of saying ‘click on the checkbox associated with the text AZ’ for example. I’ve been trying to work with Neighbor XPath, but just got totally confused. I was hoping the following would work, but sadly there are no matches…
(.//*[normalize-space(text()) and normalize-space(.)=’AL’])/preceding::input[@type = ‘checkbox’]HTMLSnippet.txt (13.1 KB)

The xpath would be:

//input[./following-sibling::label[text()='${text}']]

where ${text} is the label text.

1 Like

Brandon!!! You are AWESOME!! Thanks my friend, that works perfectly :slight_smile:

1 Like