1

I have HTML elements with custom data attributes that has different ending but starts the same (not the value but the attribute name itself). These attributes may have value or not. How could I select all of them?

<div data-validator-required> DIV 1</div>
<div data-validator-number="5.2"> DIV 2</div>
<div data-validator-submit> DIV 3</div>
<div data-validator-pattern="\d{5}-\d{3}-\d"> DIV 4</div>

I want to select all elements that has a data attribute with the name "data-validator-*" What is the correct jQuery selector for this?

2

1 Answer 1

0

Try this, and you're done...Simple and easy...

$('div').filter(function() {
  for (attr of this.attributes)
    if (attr.name.startsWith("data-validator")){
      alert($(this).text());
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-validator-required> DIV 1</div>
<div data-validator-number="5.2"> DIV 2</div>
<div data-validator-submit> DIV 3</div>
<div data-validator="\d{5}-\d{3}-\d"> DIV 4</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.