skip to Main Content
$(document).on('click', '[showsubcommentsid]', function (e) {
    e.preventDefault();
    var clickitem = $(this);
    var onoffstatus = $(this).attr("OnOffStatus");
    var hasopennedonce = $(this).attr("HasOpennedOnce");
    var labeltext = $(this).attr('label');
    var topcommentid = $(this).attr("showsubcommentsid");

    if (onoffstatus == 0 && hasopennedonce == 1) {
        $('[SubCommentsDiv=' + topcommentid + ']').css('display', '');
        clickitem.prepend('<i class="fa-solid fa-arrow-up"></i>');
        clickitem.text('Hide Comments');
        clickitem.attr("OnOffStatus", 1);
    }
    else if (onoffstatus == 1) {
        $('[SubCommentsDiv=' + topcommentid + ']').css('display', 'none');
        clickitem.prepend('<i class="fa-solid fa-arrow-down"></i>');
        clickitem.text(labeltext);
        clickitem.attr("OnOffStatus", 0);
    }

});

This code block works properly except prepending codes. I’m trying to put the i element in span element which is clickitem variable on this example but I fail.

2

Answers


  1. when you are calling clickitem.text(), it replaces the entire content of the clickitem element, including the element that you just prepended.

    Here is a way you can solve this:

    $(document).on('click', '[showsubcommentsid]', function (e) {
        e.preventDefault();
        var clickitem = $(this);
        var onoffstatus = clickitem.attr("OnOffStatus");
        var hasopennedonce = clickitem.attr("HasOpennedOnce");
        var labeltext = clickitem.attr('label');
        var topcommentid = clickitem.attr("showsubcommentsid");
    
        if (onoffstatus == 0 && hasopennedonce == 1) {
            $('[SubCommentsDiv=' + topcommentid + ']').css('display', '');
            clickitem.html('<i class="fa-solid fa-arrow-up"></i> Hide Comments');
            clickitem.attr("OnOffStatus", 1);
        } else if (onoffstatus == 1) {
            $('[SubCommentsDiv=' + topcommentid + ']').css('display', 'none');
            clickitem.html('<i class="fa-solid fa-arrow-down"></i> ' + labeltext);
            clickitem.attr("OnOffStatus", 0);
        }
    });
    
    
    Login or Signup to reply.
  2. Use template literals and toggle

    const shouldShow = (onoffstatus === '0' && hasopenedonce === '1');
    $(`[SubCommentsDiv=${topcommentid}]`).toggle(shouldShow);
    
    clickitem.html(`<i class="fa-solid fa-arrow-${shouldShow ? 'up' : 'down' }"></i> ${shouldShow ? 'Hide Comments' : labeltext }`);
    clickitem.attr("OnOffStatus", shouldShow ? '1' : '0' );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search