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?

ACs
  • 1,325
  • 2
  • 21
  • 39
  • its attribute not value so you cant get particular part of attribute – Bhargav Chudasama Nov 02 '18 at 12:52
  • 3
    Possible duplicate of [jQuery selector for elements with attribute starting with string](https://stackoverflow.com/questions/41602171/jquery-selector-for-elements-with-attribute-starting-with-string) or https://stackoverflow.com/questions/29074077/jquery-select-when-attribute-name-starting-with – Pete Nov 02 '18 at 13:20

1 Answers1

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>
ElusiveCoder
  • 1,593
  • 1
  • 8
  • 23