Wildcards in jQuery selectors

前端 未结 6 2327
逝去的感伤
逝去的感伤 2020-11-22 06:18

I\'m trying to use a wildcard to get the id of all the elements whose id begin with \"jander\". I tried $(\'#jander*\'), $(\'#jander%\') but it doe

相关标签:
6条回答
  • 2020-11-22 06:56

    for classes you can use:

    div[class^="jander"]
    
    0 讨论(0)
  • 2020-11-22 06:59

    When you have a more complex id string the double quotes are mandatory.

    For example if you have an id like this: id="2.2", the correct way to access it is: $('input[id="2.2"]')

    As much as possible use the double quotes, for safety reasons.

    0 讨论(0)
  • 2020-11-22 07:00

    Since the title suggests wildcard you could also use this:

    $(document).ready(function(){
      console.log($('[id*=ander]'));
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="jander1"></div>
    <div id="jander2"></div>

    This will select the given string anywhere in the id.

    0 讨论(0)
  • 2020-11-22 07:01

    Try the jQuery starts-with

    selector, '^=', eg

    [id^="jander"]
    

    I have to ask though, why don't you want to do this using classes?

    0 讨论(0)
  • 2020-11-22 07:01

    To get the id from the wildcard match:

    $('[id^=pick_]').click(
      function(event) {
    
        // Do something with the id # here: 
        alert('Picked: '+ event.target.id.slice(5));
    
      }
    );
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="pick_1">moo1</div>
    <div id="pick_2">moo2</div>
    <div id="pick_3">moo3</div>

    0 讨论(0)
  • 2020-11-22 07:08

    To get all the elements starting with "jander" you should use:

    $("[id^=jander]")
    

    To get those that end with "jander"

    $("[id$=jander]")
    

    See also the JQuery documentation

    0 讨论(0)
提交回复
热议问题