简体   繁体   中英

Hide a div onclick in pure javascript

I'd like to know how to hide a div onclick in pure javascript without using something like getElementById .

The goal for this is to scale and work if the number of divs is unknown.

Here is the current pattern that only hides the 1st div :

document.getElementById('msg0').addEventListener('click',function(e){
    document.getElementById('msg0').style.display = 'none';
});

And here are the sample divs :

<div class="alert alert-info" id="msg0">
    <button data-dismiss="alert" class="close">
    &times;
    </button>
    <i class="fa fa-check-circle"></i>
    Three credits remain in your account.
</div>

<div class="alert alert-success" id="msg1">
    <button data-dismiss="alert" class="close">
    &times;
    </button>
    <i class="fa fa-check-circle"></i>
    Profile details updated.
</div>

<div class="alert alert-warning" id="msg2">
    <button data-dismiss="alert" class="close">
    &times;
    </button>
    <i class="fa fa-check-circle"></i>
    Your account expires in three days.
</div>

<div class="alert alert-danger" id="msg3">
    <button data-dismiss="alert" class="close">
    &times;
    </button>
    <i class="fa fa-check-circle"></i>
    Document deleted.
</div>

Use event delegation. Only one click handler is set and works with alerts dynamically added.

document.addEventListener('click', function (event) {
    var alertElement = findUpTag(event.target, '.alert');

    if (alertElement) {
       alertElement.style.display = 'none';
    }
});

function findUpTag(el, selector) {
    if (el.matches(selector)) {
        return el;
    }

    while (el.parentNode) {
        el = el.parentNode;
        if (el.matches && el.matches(selector)) {
            return el;
        }
    }
    return null;
}

DEMO: http://jsfiddle.net/ht2qp6zj/3/

First you need to add one common class for all the div elements that need to implement this same functionality. For example lets name that class 'hideable':

/// Html
<div class='hideable'></div>

// Javascript
var elements = document.getElementsByClassName('hideable');

for(var i=0; i<elements.length; i++)
{
    var element = elements[i];
    element.addEventListener('click', onClick);
}

function onClick(event){
    event.target.style.display = 'none';
}

Something like this would suffice. This will hide only the div that is clicked on. I will explain how this works if you make a request.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("div").click(function(){
        $(this).hide();
    });
});
</script>

<div>
    one
</div> 
<div>
    two
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM