Javascript if else statement to hide and show div

Refer to the following codes:

<div id="message-1" onclick="javascript:showresponddiv(this.id)>
</div>
<div id="respond-1" style="display:none;">
</div>
<div id="message-2" onclick="javascript:showresponddiv(this.id)>
</div>
<div id="respond-2" style="display:none;">
</div>

<script type="text/javascript">
function showresponddiv(messagedivid){
    var responddivid = messagedivid.replace("message-", "respond-");
    if (document.getElementById(responddivid).style.display=="none"){
        document.getElementById(responddivid).style.display="inline";
    } else {
        document.getElementById(responddivid).style.display="none";
    }
}
</script>

The codes above already successfully make a response div when the user clicks on the message div. The response div will disappear when the user clicks on the message div again. Now my question is how to make the response of the div of the 1st message disappear when the user clicks on the 2nd message to display the response of the second message?

0
source share
2 answers

You should give the “responding” divs a generic class:

<div id="respond-1" class="response' style="display:none;"></div>

Then you can get all the divs with getElementsByTagName, compare the class and hide them according to:

function hideAllResponses() {
    var divs = document.getElementsByTagName('div');
    for(var i = divs.length; i-- ;) {
        var div = divs[i];
        if(div.className === 'response') {
            div.style.display = 'none';
        }
    }
}

getElementsByClassName, IE8 . , , , , ( querySelectorAll). .


:

  • javascript: , . :

    onclick="showresponddiv(this.id)"
    
  • DOM , , ​​ jQuery, .


: , , :

var current = null;

function showresponddiv(messagedivid){
    var id = messagedivid.replace("message-", "respond-"),
        div = document.getElementById(id);

    // hide previous one
    if(current && current !== div) {
        current.style.display =  'none';
    }   

    if (div.style.display=="none"){
        div.style.display="inline";
        current = div;
    } 
    else {
        div.style.display="none";
    }
}

: ​​. . DEMO.

+5

div id = "reply -"

e.g

<div id="respond-1" class="classname" style="display:none;"></div>
<div id="respond-2" class="classname" style="display:none;"></div>

"showresponddiv()" divs "classname" .

jQuery :

$(".classname").hide();

jQuery - Javascript, DOM .

Sizzle - CSS CSS, jQuery DOM

0

All Articles