HTML:
<div onclick="doSomething()" id="parent">
<div id="child"></div>
</div>
CSS:
#parent {
background-color: blue;
width: 100%;
height: 100px;
}
#child {
background-color: green;
width: 50%;
height: inherit;
}
.myClass {
background-color: red !important;
}
JS:
function doSomething() {
event.target.className = ('myClass');
}
As you can see in this JSFIDDLE, upon clicking the child, instead of applying the class to the parent which triggers the function, it applies it to the child. I want to know how to avoid this and apply it to the parent no matter where I click inside of it. I am trying to avoid using the document.getElement(s)ByClass/Id
method.
Any help?
You can refer to the element that handles the event with currentTarget
.
Identifies the current target for the event, as the event traverses the DOM. It always refers to the element the event handler has been attached to as opposed to
event.target
which identifies the element on which the event occurred.
However, instead of relying on the browser to provide a global event
object, I would pass it to the function:
onclick="doSomething(event)"
You can also refer to the element the handler is bound to with this
:
onclick="doSomething(event, this)"
Of course please consider to not use inline event handlers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With