Closed
Description
Describe the feature you'd like:
When I have an anchor with some nested elements like this:
<a
href="https://www.example.com"
role="button"
>
<span>
<span class="some-icon-class" />
<span>Click here!</span>
</span>
<span class="MuiTouchRipple-root" />
</a>
I would love to have an easy way to get this anchor with a function like
getAnchorByText()
queryAnchorByText()
that returns the anchor when I say getAnchorByText('Click here!')
.
Suggested implementation:
I did not look into that yet as I want to make sure others consider this feature as useful as well. If yes I might find the time to create a PR.
Describe alternatives you've considered:
2 possible (not so beautiful) workarounds would be:
- Adding a test id to an additional wrapper and look for the anchor like that (The problem is that I use an external library to render the link, so I cannot give the link it's own test id):
getByTestId('button-wrapper').querySelector('a')
- Search for the text and go up the DOM tree manually (and pray that the external component will never change its nesting)
getByText('Click here!').parentNode.parentNode
Alternative
There are other HTML elements than anchors that people might want to query for. So if it is preferred we could make it an universal function:
getElementByText(<ElementName>, <Text>)
This would always return the closest element (of the type ElementName
) of the text found when you go up the DOM tree.
In my example above I would use it like this:
getElementByText('a', 'Click here!')