Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle only div containing same text

HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="event">
  <div class="clicker">
    click
  </div>
  <div class="title">
    <a href="#">first event</a>
  </div>
</div>
<div class="event">
  <div class="clicker">
    click
  </div>
  <div class="title">
    <a href="#">first event</a>
  </div>
</div>
<div class="event">
  <div class="clicker">
    click
  </div>
  <div class="title">
    <a href="#">second event</a>
  </div>
</div>
<div class="event">
  <div class="clicker">
    click
  </div>
  <div class="title">
    <a href="#">second event</a>
  </div>
</div>
<div class="event">
  <div class="clicker">
    click
  </div>
  <div class="title">
    <a href="#">second event</a>
  </div>
</div>
<div class="event">
  <div class="clicker">
    click
  </div>
  <div class="title">
    <a href="#">second event</a>
  </div>
</div>

This gives me a foo class for every first instance of event in a group with the a tag with the same text.

Now I would like that, whenever I click a clicker, I want all the .event divs with same .event .title a text to reappear.

(code updated to show proper structure and why the solution didn't work. whenever i click on "clicker", it applies the code to ALL events)

like image 397
Ido Angel-Bohadana Avatar asked Dec 31 '25 14:12

Ido Angel-Bohadana


1 Answers

You need to attach a click event to the event class, then when the user clicks the div you could get the text of the anchor and use contains selector to filter the event with the same title text :

$('.event').click(function() {
  $('.event a:contains(' + $('a', this).text() + ')').closest('.event').toggleClass('foo');
});
.foo {
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="event">
  <div class="title">
    <a href="#">first event</a>
  </div>
</div>
<div class="event">
  <div class="title">
    <a href="#">first event</a>
  </div>
</div>
<div class="event">
  <div class="title">
    <a href="#">second event</a>
  </div>
</div>
<div class="event">
  <div class="title">
    <a href="#">second event</a>
  </div>
</div>
<div class="event">
  <div class="title">
    <a href="#">second event</a>
  </div>
</div>
<div class="event">
  <div class="title">
    <a href="#">second event</a>
  </div>
</div>
like image 58
Zakaria Acharki Avatar answered Jan 03 '26 03:01

Zakaria Acharki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!