Reputation: 1055
Consider the below ReactJs component:
import React from 'react';
const TestOptions = (props) => (
<li className={props.className} onClick={(event) => props.clickTestOptions(event)}>
{
React.createElement(
'div',
{
className: 'opt-wrap',
dangerouslySetInnerHTML: {
__html: props.details.answer
}
}
)
}
</li>
);
export default TestOptions;
In parent component I have the following function.
clickTestOptions = (event) => {
console.log(event.target);
}
The console sometime give me either one of the following result:
<div class="opt-wrap">Mathematics</div>
or,
<li class="mc-opt-cls"><div class="opt-wrap">Mathematics</div></li>
I need always the li element not the div, What is the solution?
Upvotes: 0
Views: 54
Reputation: 29194
I think you want event.currentTarget
, which always refers to the element the listener is attached to.
Upvotes: 1
Reputation: 1055
For now my solution is:
let targetOpt = event.target;
console.log('targetOpt:', targetOpt);
if (!targetOpt.classList.contains("mc-opt-cls")) {
targetOpt = findParentWithClass(event.target, 'mc-opt-cls');
}
console.log('targetOpt:', targetOpt);
findParentWithClass is my helper function:
export const findParentWithClass = (el, cls)=> {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
};
Upvotes: 0