Home > database >  jQuery selector with RegEx not accepting expressions
jQuery selector with RegEx not accepting expressions

Time:06-04

I am trying to get all elements with 'aria-label' attribute that contains special characters:

<div aria-label="FromTo #abc124">Accept</div>
<div aria-label="FromTo #dd_13">Accept</div>
<div aria-label="FromTo #_bd33">Accept</div>
<div aria-label="FromTo #kld9L">Accept</div>

I would like to iterate those elements in jQuery, but every regular expression I've tried gave me unexpected expression error.

Some expressions I tried so far:

$('[aria-label="FromTo #*"]') // not working
$('div').filter(function() {
    return $(this).attr('aria-label').match(/FromTo \#.*/);
}) // not working
$(':contains([aria-label="FromTo [#\w \d ]")') // not working

Nothing.

CodePudding user response:

Selectors don't test regular expressions, but you don't need it here. There's an "attribute starts with" selector, attr^=string.

console.log($('div[aria-label^="FromTo #"]').length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div aria-label="FromTo #abc124">Accept</div>
<div aria-label="FromTo #dd_13">Accept</div>
<div aria-label="FromTo #_bd33">Accept</div>
<div aria-label="FromTo #kld9L">Accept</div>
<div area-label="something else">Not accept</div>
<div>Not ARIA</div>

  • Related