Objective

Given an HTML document, determine if a click occurred anywhere inside a <div> element.

Difficulty

Easy

Description

Consider the following HTML document:

<h1>"Div Clicked?" Exercise</h1>

<div>Div 1</div>

<p>This is a paragraph.</p>

<div>
   Div 2
   <button>A button</button>
</div>

<p>This is another paragraph.</p>

<div>
   Div 3
   <h2>A sub-heading</h2>
   <p>This is yet another paragraph with a <span>span inside it</span>.</p>
</div>

along with the generic styles shown below:

div {
   background: #eee;
}

The result could be seen as follows:

Live Example

Now in this exercise, you have to set up a click handler on window to determine if a click occurs anywhere on this document from within a <div> element.

If this is the case, the program must alert the text "Div clicked!". Otherwise, it should do nothing.

For instance, the click could be made on the <span> element, which is nested inside a <p> element, which is nested inside a <div> element. Consequently, the alert must be shown in this case.