Get DIV ID onClick - to hide DIV when click outside in Javascript

How can I get the ID of specific DIV element using onClick event ? I have a couple of DIVs and I need to hide them when users click on the specific DIV that is used as a semi-transparent background. I am looking for a javascript solution.
give a positive ratinggive a negative rating
07 Jan 2022 at 03:09 PM

To hide a DIV element with other DIV elements inside, when click on a specific DIV, you can use the javascript solution below. It compares if clicked element is the same as element identified with getElementById. This solution can be used for example on image preview.


document.onclick = function(e) {
var d = document.getElementById('first');
if( == d) {'none'; }


<div id='first'>
<div id='second'>Text</div>

When the "first" DIV is used as a full screen background with transparency and you click on the content in the "second" DIV, then nothing should happen. But when you click on the "first" DIV, the javascript function should hide both, the first and the second one.
give a positive ratinggive a negative rating
07 Jan 2022 at 07:14 PM
Share on FacebookShare on TwitterShare on LinkedInSend email
2023 AnswerTabsTermsContact us
How would you rate your experience with AnswerTabs ?
Very badVery good
Thank you for your feedback.