Ido Angel-Bohadana
Ido Angel-Bohadana

Reputation: 165

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)

Upvotes: 3

Views: 74

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

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>

Upvotes: 2

Related Questions