How to make the HTML element without clicking?
Each element is clicked by JavaScript. Clicking on the element gets the alert(this.id)
. How do I make parent2
not clickable, but the button inside allows you to click?
Of course I will have more parent3
, parent..4
with div inside and forms. Is there a simple way?
It will help if there is a way to click it all within the parent(childs). Parent2, parent3 ... not to click, but form inside Parent2..,3..to be clickable
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId;
for (var i = 0; i < divCount; i += 1) {
div[i].onclick = function(e) {
clickedDivId = this.id;
event.stopPropagation();
alert(this.id);
};
}
#parent {
width: 450px;
height: 170px;
margin: 10px;
padding: 10px;
background-color: blue;
}
#parent2 {
width: 450px;
height: 170px;
margin: 10px;
padding: 10px;
background-color: blue;
}
#parent3 {
width: 450px;
height: 170px;
margin: 10px;
padding: 10px;
background-color: blue;
}
#child {
width: 430px;
height: 70px;
margin: 10px;
float: left;
background-color: red;
}
<div id="parent">
<div id="child"></div>
</div>
<div id="parent2">
<button type="button" onclick="alert('Hello world!')">Click Me!</button>
</div>
<div id="parent3">
<button id="button" type="button" onclick="alert('Hello world2!')">Click
Me!</button>
</div>
If you want your
parent2 div
to not run any code, justreturn
when theclickedDivId == "parent2"
.If you have multiple
divs
then you can assign them a class and in the event handler check if that class is present for that clickeddiv
Add id or something for the button and check if the event was originated from it using the e.target. Below is the snippet
instead of attaching
on-click
event on div put it on button only and that event handler should implement alert andstopPropagation
logic.No need to attach any
onClick
event ondiv
You Code should be like
HTML
Javascript :
This would exclude
parent2
from you onclick event:Altough I think it would be better to solve this with a class:
You can add some CSS code to button like :
with this code button get a level higher than parent box, remember parent box must have
position:relative