Search code examples
javascriptchildren

Hide elements if its childNodes are empty


My goal is to append button for hiding replies on comments and don't show this button if there are no replies for each comment.

Please, don't blame me so much for this code because I'm newbie and learning hard.

Here's the code:

var replies = document.querySelectorAll(".comments_list > .comment_item > .reply_comments"); //should check if .childNodes.length === 1  
var comments = document.querySelectorAll(".comments_list > .comment_item");
var combodys = document.querySelectorAll(".comments_list > .comment_item > .comment_body");

addBtn();

function addBtn() {
  for (var i = 0; i < comments.length; i++) {
    var combody = combodys[i];
    var btn = document.createElement("input");
    btn.type = "button";
    btn.className = "hidereplies";
    btn.value = "show replies";
    combody.appendChild(btn); //don't show if replies.childNodes.length === 1
  }
}

After button added I want to check if comments contain replies and hide button when replies block is empty. Tried to check childNodes method and faced with problem that I have to "+1" to current "hidereplies" button value:

if (replies[6 + 1].childNodes.length === 1) {
document.querySelectorAll(".hidereplies")[6].style.display = "none";
}

So, for now I don't know how to cycle through all comments and hide "hidereplies" button if there are no replies.

Hope for a help to solve this problem in plain Javascript. Thanks in advance!


Solution

  • Try

    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); //don't show if replies.childNodes.length === 1
                }
            }
        }
    }
    addBtn();
    

    Demo: Fiddle