0

I'm having difficulties finding a solution for my problem. I have a collection of elements which have the same class name. They are all hidden and I have a button which should display the specific element. I can cycle trough all of the elements, but my code display ALL of them instead of only the one i clicked.

So I have to specify the current element which I want to change, maybe with "this"?

The usage of class names can be changed. Hope you can help me.

function checkDoublettesLAS() {
  var doublettes = document.getElementsByClassName('checkSuccess');

  for (var i = 0, n = doublettes.length; i < n; i++) {
    $(doublettes[i]).css('display', 'block');
  }
}
<div class="check">
  <span class="checkSuccess" hidden>
    foodummy1
  </span>
  <button onClick="checkDoublettesLAS();return false;">
    Show Text
  </button>
  <span class="checkSuccess" hidden>
    foodummy2
  </span>
  <button onClick="checkDoublettesLAS();return false;">
    Show Text
  </button>
  <span class="checkSuccess" hidden>
    foodummy3
  </span>
  <button onClick="checkDoublettesLAS();return false;">
    Show Text
  </button>
  <span class="checkSuccess" hidden>
    foodummy4
  </span>
  <button onClick="checkDoublettesLAS();return false;">
    Show Text
  </button>
  <span class="checkSuccess" hidden>
    foodummy5
  </span>
  <button onClick="checkDoublettesLAS();return false;">
    Show Text
  </button>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
isherwood
  • 58,414
  • 16
  • 114
  • 157
coyan
  • 11
  • 5
  • @Cerbrus i just noticed that i was missing the buttons in the elements. each element has a button which should display only the corresponding element. – coyan Aug 31 '22 at 14:20
  • @T.J.Crowder nah not really. the span tag could also be changed to p or something else – coyan Aug 31 '22 at 14:21
  • 1
    Protip: Use [event handlers](https://api.jquery.com/click/), not inline JavaScript. – isherwood Aug 31 '22 at 14:24
  • There are thousands of questions on SO about DOM traversal with jQuery, which has numerous methods for doing so (`next()`, `closest()`, `siblings()`, etc.). Have a look into that, as well as the magic of `$(this)`. – isherwood Aug 31 '22 at 14:27
  • Please check this fiddle out. I tried to explain it with the comments as much as I can. I hope it might help you to understand a bit. https://jsfiddle.net/z2Lv7qm9/ – Mikail Çolak Aug 31 '22 at 14:51
  • Attach a listener to the container, check to see if the clicked element is a button, and then remove a hidden class [from the `previousElementSibling`](https://jsfiddle.net/7uxjqLnz/1/). – Andy Aug 31 '22 at 15:35
  • @MikailÇolak & andy thank you for your suggetions, i got the code to work! – coyan Sep 01 '22 at 10:22

0 Answers0