[Final Edit: I feel compel to response as I learned a LOT from this post(mainly through you guys, and I spend more time understanding CSS.. but at the end, I really don't have any good idea how to make this work.. other than really destroying the basic structure of html.. which I didn't want to do. but I did... (for whatever reason #parent>* { color: black } would not work when I click on child)..
Here's what i did but if you now know what I was trying to do.. please see if you can correct me w/ real answer as I feel like this can't be this hackery to get it going.
CSS
.red {
color: red;
}
div[id*="child"] {
color: black;
}
div [id*="alterChild"]{
color: green;
JS
;(function(){
let parentId = document.getElementById('parent');
parentId.addEventListener('click', function(e){
if (e.target.id === 'parent') {
e.target.className = "red";
} else {
e.target.setAttribute("id", "alterChild");
}
},false);
})(
HTML
<div id="main">MAIN
<div id="parent">parent
<div id="child1">child1</div>
<div id="child2">child2</div>
<div id="child3">child3</div>
</div>
</div
__________END OF FINAL EDIT___________
So I want to fire only on parent when parent is clicked. Below code, it fires on parent + all its children. How can I prevent this? I try w/ stop/prevent both before and after to see if I have any luck.
Please advise.
- when click on parent, only parent should get class "red". (and not it's children).
- When any child is clicked, no parent should be red nor any other none clicked child(which was already working).
<div id="main">MAIN
<div id="parent">parent
<div id="child1">child1</div>
<div id="child2">child2</div>
<div id="child3">child3</div>
</div>
</div>
;(function(){
let parentId = document.getElementById('parent');
parentId.addEventListener('click', function(e){
e.stopPropagation();
e.preventDefault();
e.target.className = "red";
e.stopPropagation();
e.preventDefault();
},false);
})()