I have a bunch of elements that contain data-testid
attributes.
Think of them as something like this:
<div data-testid="my-page">
<div data-testid="my-page-content"></div>
<div data-testid="my-page-footer">
<button data-testid="my-page-action-button">Do something</button>
<button data-testid="my-page-cancel-button">Cancel</button>
</div>
</div>
For one of my tests, I need to find the buttons through their data test id pattern.
As you can see, it is my-page-**-button
.
I need to know how to adjust my selectors accordingly so that I grab the elements that begin with my-page
and end with button
.
So far, I've been doing:
$("[data-testid^='my-page-']")
Unfortunately, this will grab my-page-content
(or my-page-footer
). How can I grab all elements with data-testids like my-page-**-button
?
CodePudding user response:
either include the button
button[data-testid^='my-page-']
or include the ends with
[data-testid^='my-page-'][data-testid$='button']
console.log($("button[data-testid^='my-page-']").length);
console.log($("[data-testid^='my-page-'][data-testid$='button']").length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-testid="my-page">
<div data-testid="my-page-content"></div>
<div data-testid="my-page-footer">
<button data-testid="my-page-action-button">Do something</button>
<button data-testid="my-page-cancel-button">Cancel</button>
</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Select with prefix AND Suffix .
$("[data-testid^='my-page-'][data-testid$='-button']")
RULE in general
- Execulsive AND : do not keep space between selector(s)
- Accumulative AND: put
,
between selector(s)
You need here the Execulsive AND
CodePudding user response:
I think this does what you need:
$('[data-testid^=my-page-][data-testid $=button')
A working demo is below, let me know if you needed something else.
DEMO
// Select using start and end selectors
$('[data-testid^=my-page-][data-testid $=button').each( function() {
console.log($(this).attr("data-testid"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-testid="my-page">
<div data-testid="my-page-content"></div>
<div data-testid="my-page-footer">
<button data-testid="my-page-action-button">Do something</button>
<button data-testid="my-page-cancel-button">Cancel</button>
</div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>