Rubioli Rubioli - 6 months ago 11
Javascript Question

Remove class from div with loop/array

I have 4 divs with same Class and Id. What I am looking for is to remove

display-none
-class on that specific div whenever
#button
is clicked.

What I have done now is to give an additional class name to each div so they are more "recognizable" for jQuery.

Here is my code:

html

<div class="parentdiv">
<h3 id="button">remove class</h3>
<div class="display-none" id="element">
Show me on button click
</div>
</div>


jquery

$('h3#button').each(function(i){
$(this).addClass('remove-btn-' + (i+1));
});

$('div#element').each(function(i){
$(this).addClass('remove-this-' + (i+1));
});


So What I am looking for is to loop through
remove-this-1
,
remove-this-2
etc and remove
display-none
class when ever
remove-btn-1
,
remove-btn-2
etc is clicked.

Answer
  1. Use one more class to the div which has display-none class
  2. give same class to each button
  3. wrap them in a parent them
  4. use this to achieve your goal

Whenever you click on the button, it will look for class box of current clicked the button. For demo purpose - I have applied CSS to display-none class, So that you can see changes.

$(document).ready(function(){
   $('.button').click(function(){
     $(this).prev('.box').removeClass('display-none');
   });
});
.display-none {
  display: inline-block;
  padding: 5px;
  background: tomato;
  color: #fff;
  border-radius: 3px;
}
.button {
  display: inline-block;
  padding: 5px;
  background: steelblue;
  color: #fff;
  border-radius: 3px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <div class="display-none box">Lorem ispum 0...</div>
  <p class="button">Remove Class</p>
</div>

<div class="parent">
  <div class="display-none box">Lorem ispum 1...</div>
  <p class="button">Remove Class</p>
</div>

<div class="parent">
  <div class="display-none box">Lorem ispum 2...</div>
  <p class="button">Remove Class</p>
</div>

<div class="parent">
  <div class="display-none box">Lorem ispum 3...</div>
  <p class="button">Remove Class</p>
</div>