How to select elements with jQuery that have a certain value in a data attribute array

后端 未结 2 1956
南方客
南方客 2020-12-09 21:32

is there a way in jQuery to select elements that have a certain value in a data attribute array?

Consider this snippet of html:

  • 相关标签:
    2条回答
    • 2020-12-09 22:05

      try something like :

      $('li[data-city*="New York"]')
      

      Attribute Contains Selector [docs]

      jsfiddle example

      0 讨论(0)
    • 2020-12-09 22:17

      You can use the selector tag[attr*=string] where *= matches the string found anywhere in the tag value. I have colored the text red, just so you can test...

      $("li[data-city*=New York]").css({color:'red'});
      

      Or via more complex method to fit needs of example two:

      $("li")
          .filter( function(){ 
                  return $(this).attr('data-city').match(/(^|,\s+)London(,|$)/) 
              })
          .css({color:'red'});
      

      This method uses filter to go through the list of selected li and match all elements with attribute data-city that matches regex (^|,\s+)London(,|$) which means...

      • start or comma (^|,)
      • and one or more spaces (\s+)
      • followed by London
      • followed by comma or end (,|$)

      I used this HTML:

      <li id="person1" data-city="Boston, New York, San Fransisco, London">
          Person name 1
      </li>
      <li id="person2" data-city="Boston, New Jersey, London, San Fransisco">
          Person name 2
      </li>
      <li id="person3" data-city="Los Angeles, New York, New London, Washington">
          Person name 3
      </li>
      
      0 讨论(0)
    提交回复
    热议问题