Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select an element by particular pattern with jquery

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading