简体   繁体   中英

how to select all elements with matching attribute of this in jQuery?

I would like to select all elements within a div that have the same attribute as the selected element, using the this selector.

So in my example, when I click on an element with a class of .foo , I would like to find all elements within .container that share the same data-index attribute as the element that was clicked and then add the class of .bah . Currently the function I have only adds .bah to the element that was clicked on, I understand how to select certain attributes but not in relation to the this selector.

Javascript:

$(document).on('click','.foo', function() {
        $(this).addClass('bah');
});

HTML:

<div class="container">
  <div class="inner1">
    <div data-index="0" class="foo">
      <p>item 1</p>
    </div>
    <div data-index="2" class="foo">
      <p>item 2</p>
    </div>
  </div>
  <div class="inner2">
    <div data-index="0" class="foo">
      <p>item 1</p>
    </div>
    <div data-index="2" class="foo">
      <p>item 2</p>
    </div>
  </div>
</div>
$(document).on('click','.foo', function() {
    var dataIndex = $(this).data('index');
    $(document).find("div[data-index='" + dataIndex + "']").each(function() {
        $(this).addClass('bah');
    });
});

Example Fiddle: http://jsfiddle.net/9huw0ym9/1/

You can use .filter() to get the result.

$(document).on('click','.foo', function() {
    var dataIndex = $(this).data('index');
    $('.container div').filter(function(){
        return $(this).data('index') === dataIndex
    }).addClass('bah');
});

Or using attribute based selector.

$(document).on('click','.foo', function() {
    var dataIndex = $(this).data('index');
    $('.container div[data-index="'+dataIndex+'"]').addClass('bah');
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM