Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to target element by first four letters of its ID?

Tags:

html

jquery

I'm trying to select one of the parent elements through the first four letters of its id for the following two reasons:

a - The IDs vary. b - The nesting level varies.

See example:

<div id="zone1">
    <div class="child"></div>
</div>

<div id="zone2">
    <div id="something-else">
       <div class="child"></div>
    </div>
</div>

and the jQuery I want to achieve needs to find the parent div who's id starts with the letters 'zone,' as such:

$('.child').click(function(){
   $(this).parents('#zone....').doSomething();
});

Is there a way to do this? Or at least a thought on how to go about reaching that parent div?

Thanks a lot for your help.

like image 966
Mo Alsaedi Avatar asked Dec 09 '25 06:12

Mo Alsaedi


1 Answers

You can use the attribute starts with selector

$('.child').click(function(){
   $(this).closest('[id^="zone"]').doSomething();
});
like image 173
adeneo Avatar answered Dec 10 '25 18:12

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!