Select elements with id attribute that starts/ends with a particular value

后端 未结 7 1278
予麋鹿
予麋鹿 2020-12-05 17:55

Can jQuery or JavaScript be used with a regex to select multiple elements with similar id?

I have the following paragraphs:

相关标签:
7条回答
  • 2020-12-05 18:08

    Here is the working JS FIDDLE

    HTML:

    <p id="item5_2"> A </p>
    <p id="item9_5"> B </p>
    <p id="item14_2"> C </p>
    <input type="button" value="Get element ids starting with 'item' and ending with '2'" onclick="get_ids()">
    

    JS:

    get_ids = function(){
        $('[id^="item"][id$="2"]').each(function() {
            alert($(this).attr('id'));
        });
    }
    
    0 讨论(0)
  • 2020-12-05 18:10

    You can use "start with" and "ends with" selectors provided by jQuery, like below.

    $("[id^='item'][id$='2']").html("D");
    

    Official documentation:

    • Start with selector
    • Ends with selector
    0 讨论(0)
  • 2020-12-05 18:12

    You can combine attribute selectors: fiddle

    $("[id^='item'][id$='2']").html("D");
    
    0 讨论(0)
  • 2020-12-05 18:17

    The best way to go is to use the following jQuery selectors

    ^= is starts with
    $= is ends with
    
    =  is exactly equal
    != is not equal
    *= is contains
    

    So in your case:

    var $items = $('[id^="item"][id$="2"]');
    
    0 讨论(0)
  • 2020-12-05 18:18

    You can use next code if you want to do any other action:

    $('[id^="item"]').each(function(){
      if(this.id.slice(-1) == 2){
        //Do something
        $(this).html('D');
      }
    
    });
    
    0 讨论(0)
  • 2020-12-05 18:20

    Try this

     <p id="item5_2"> A </p>
     <p id="item9_5"> B </p>
     <p id="item14_2"> C </p>
    

    and...

     $('[id^="item"][id$="2"]')
    
    0 讨论(0)
提交回复
热议问题