Hide and Unhide DIV with dynamic php ID using Javascript

I am trying to hide and unhide a div tag that houses a textfield. These textfield would be displayed on each record. I have this function that works when i use a single string as an id only issue is it displays on all the rows. So i decided to add an variable that matches each row to the ID so when a user clicks it shows just the textarea of that particular row. Below is my code

Javascript:

<script>
    const targetDiv = document.getElementById("third");
    const btn = document.getElementById("<?php echo $author_id_4comm; ?>");
    btn.onclick = function () {
        if (targetDiv.style.display !== "none") {
            targetDiv.style.display = "none";
        } else {
            targetDiv.style.display = "block";
        }
    };    
</script>

HTML:

<a class='btn' id='$author_id_4comm' role='button' style='font-size:11px;color:#808080;' > Reply Comment</a>
<div id='third' style='display:none;'>Display textfield here</div>

The problem now when i click on the reply button, the hidden div shows only on the last row.

Kindly assist me!

Answer

In order to keep things DRY, I recommend using classes instead of IDs.

Based on your code structure, field containers are immediate siblings of buttons. Bind a click event to each button. Upon button click, find the nextElementSibling and toggle() its “show” class.

const btns = document.querySelectorAll(".btn");

function handleButtonClick() {
  let field = this.nextElementSibling;
  field.classList.toggle('field--show');
}

btns.forEach(btn => btn.addEventListener('click', handleButtonClick));
.btn {
  font-size: 11px;
  color: #808080;
}

.field {
  display: none;
}

.field--show {
  display: block;
}
<a class="btn" role="button">Reply Comment</a>
<div class="field">Display textfield here</div>
<a class="btn" role="button">Reply Comment</a>
<div class="field">Display textfield here</div>
<a class="btn" role="button">Reply Comment</a>
<div class="field">Display textfield here</div>

Alternatively, if you want to show only the item that was clicked, hide all fields before showing the target field:

const btns = document.querySelectorAll(".btn");
const fields = document.querySelectorAll(".field");

function handleButtonClick() {
  let field = this.nextElementSibling;
  fields.forEach(field => field.classList.remove('field--show'));
  field.classList.add('field--show');
}

btns.forEach(btn => btn.addEventListener('click', handleButtonClick));
.btn {
  font-size: 11px;
  color: #808080;
}

.field {
  display: none;
}

.field--show {
  display: block;
}
<a class="btn" role="button">Reply Comment</a>
<div class="field">Display textfield here</div>
<a class="btn" role="button">Reply Comment</a>
<div class="field">Display textfield here</div>
<a class="btn" role="button">Reply Comment</a>
<div class="field">Display textfield here</div>