Is there a way to select all id's with jQuery with a prefix "my" and a suffix "0-9". Something like these $("#my$1-4") or is it just possible with a loop ?
<div id="my1"/>
<div id="my2"/>
<div id="my3"/>
<div id="my4"/>
<div id="my5"/>
jQuery select() MethodThe select event occurs when a text is selected (marked) in a text area or a text field. The select() method triggers the select event, or attaches a function to run when a select event occurs.
Syntax of jQuery Select Option$("selector option: selected"); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $("selector option: selected").
Description. "$("div p")" Selects all elements matched by <div> that contain an element matched by <p>.
The prefix part is easily achievable with an attribute starts-with selector:
$("div[id^=my]");
But there is no selector that will allow you to specify a range of characters, so a loop will have to be involved. I would suggest filter:
$("div").filter(function () {
return /^my\d$/.test(this.id);
});
First thoughts, which seems to work well:
$('div[id^="my"]').filter(
function(){
return this.id.match(/\d+$/);
});
JS Fiddle demo.
The above selects all div elements whose id starts with the value my, and then filters the returned elements to those whose id also ends with numeric characters.
References:
filter().If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With