JSFiddle - React, Tailwind, and code Playground

by glebcha

HTML

<div class="comments_list">
    <div class="comment_item">
        <div class="comment_body">test1 - comments</div>
        <div class="reply_comments">
            <div class="comment_body">want to hide only current ".reply_comments"</div>
        </div>
    </div>
    <div class="comment_item">
        <div class="comment_body">test2 - comments</div>
        <div class="reply_comments">
            <div class="comment_body">but not all</div>
        </div>
    </div>
    <div class="comment_item">
        <div class="comment_body">test3 - no comments</div>
        <div class="reply_comments"></div>
    </div>
</div>

JavaScript

hideReplies ();
  
  function hideReplies () {
  
function getChildrenByClassName(el, className) {
    var children = [];
    for (var i = 0; i < el.childNodes.length; i++) {
        if (el.childNodes[i].className == className) {
            children.push(el.childNodes[i]);
        }
    }
    return children;
}

function addBtn() {
    var comments = document.querySelectorAll(".comments_list > .comment_item"),
        comment, combody;

    for (var i = 0; i < comments.length; i++) {
        comment = comments[i];
        var replies = comment.querySelectorAll('.reply_comments .comment_body');
        if (replies.length > 0) {
            combody = getChildrenByClassName(comment, 'comment_body')[0];
            if (combody) {
                var btn = document.createElement("input");
                btn.type = "button";
                btn.className = "hidereplies";
                btn.value = "show replies";
                combody.appendChild(btn); 
            }
        }
    }
}
addBtn();


function hideR() {
var buttons = document.querySelectorAll(".hidereplies");

for (a = 0; a < buttons.length; a++) {
    var btn = buttons[a];
    btn.onclick = function (event) {
        var btn = event.currentTarget;
        var comments = btn.parentNode.querySelectorAll(".reply_comments");
        for (var y = 0; y < comments.length; y++) {
            var reply = comments[y];
            reply.style.display = (reply.style.display != 'none' ? 'none' : 'block');
        }
    };
}
}
hideR();

    
}