Find div with attribute value equal to the one selected with jquery

Asked

Viewed 453 times

1

I have several buttons with data-numBtn numeric and with value equal to that of div (with attribute data-slide) that controls. In short, I’d like to click e.g. on .btn with data-numBtn="3" something happens (eg fadein) to .img with data-slide="3" also. PS: The elements will be loaded dynamically, without sight of how many will be, the elements data-numBtn and data-slide will always match.

HTML:

<div class="btn" data-numBtn="1">...</div>
<div class="btn" data-numBtn="2">...</div>
<div class="btn" data-numBtn="3">...</div>
<div class="btn" data-numBtn="4">...</div>

<div class="img" data-slide="1">...</div>
<div class="img" data-slide="2">...</div>
<div class="img" data-slide="3">...</div>
<div class="img" data-slide="4">...</div>

2 answers

2


If your elements are loaded dynamically you will need to delegate this event. So I suggest using $(document).on('click', '.btn', function(){ who will search for the element with the class btn only when the click appears and not when it loads the code in case it is not there yet.

To read this attribute data can use the .data() jQuery. A possible code for this problem would be:

$(document).on('click', '.btn', function(){
    var numBtn = $(this).data('numBtn');
    $('.img[data-slide="' + numBtn + '"]').fadeIn();
});

In case there are numbers that collide with each other you will need to use the .index() to find out the position of .btn relative to others, ignoring the attribute data. If that’s your case, you can use it like this:

$(document).on('click', '.btn', function(){
    var numBtn = $(this).index();
    $('.img[data-slide]').eq(numBtn);
});
  • Since you’re not doing any other operation with numBtn could remove it and use directly on selector (first code) or jQuery.eq() (second)

  • @Brunoaugusto true. As it suggests would be smaller the code. I left so to be clearer, step by step.

1

You can select the image using the class .img and the attribute itself data-slide. To select the image 3:

$('.img[data-slide="3"]');

To select the image corresponding to the button, simply:

$('.btn').on('click',function(){
   var btnId = $(this).attr('data-numBtn'); // pega o id do botão clicado
   var $img = $('.img[data-slide="'+btnId+'"]'); // seleciona a imagem correspondente ao id do botão clicado

   $img.fadeIn(); 
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.