Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Select # id with word as prefix and counter as suffix

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"/>
like image 764
MR.ABC Avatar asked Jun 23 '12 21:06

MR.ABC


People also ask

What is select in jQuery?

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.

How do I select a specific Dropdownlist using jQuery?

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").

What does $( div p select?

Description. "$("div p")" Selects all elements matched by <div> that contain an element matched by <p>.


2 Answers

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);
});
like image 146
James Allardice Avatar answered Sep 29 '22 20:09

James Allardice


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:

  • attribute-starts-with selector.
  • filter().
  • Regular Expressions, at Mozilla Developer Network.
like image 21
David Thomas Avatar answered Sep 29 '22 21:09

David Thomas