skip to Main Content

i got a JS Script that shows/hides share icons, wheren a sharebutton is clicked.
The page has multiple sharebuttons on the page. How can I turn it to only toggle those elements in the same row as the button? Currently my Script toggles ALL icons at once.
For example: imagine a joblisting with a sharebutton for every job.

Currently im using

function hideInactive() {
    var x = document.getElementsByClassName('social_icons');

    console.log(x.length);

    for (let i = 0 ; i < x.length; i++) {
        if (x[i].style.display === "inline") {
            x[i].style.display = "none";
        } else {
            x[i].style.display = "inline";
        }
    }
}

But this obviously toggles all icons at once. and not only the relevant ones.

2

Answers


  1. Use jQuerys closest() function to find your parent row, then you can select all buttons in that parent row:

    $(function(){
    
      $("button").on("click", function(){
         const parentRow = $(this).closest(".row");
         $(parentRow).find("button").css("display", "none");
      });
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="row">
      Row 1
      <button>Row 1 button A</button>
      <button>Row 1 button B</button>
    </div>
    
    <div class="row">
      Row 2
      <button>Row 2 button A</button>
      <button>Row 2 button B</button>
    </div>
    
    <div class="row">
      Row 3
      <button>Row 3 button A</button>
      <button>Row 3 button B</button>
    </div>
    Login or Signup to reply.
  2. $(function(){
    
      $("button").on("click", function(){
         const parentRow = $(this).closest(".row");
         $(parentRow).find("button").css("display", "none");
      });
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="row">
      Row 1
      <button>Row 1 button A</button>
      <button>Row 1 button B</button>
    </div>
    
    <div class="row">
      Row 2
      <button>Row 2 button A</button>
      <button>Row 2 button B</button>
    </div>
    
    <div class="row">
      Row 3
      <button>Row 3 button A</button>
      <button>Row 3 button B</button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search