Reputation: 351
If I click on one or two I'll get the object of whole ul
tag, but from this object I want to get access to the li
tag objects and I am not able to get how
function on(a){
console.log(a);
}
<ul onclick=on(this)>
<li>one</li>
<li>two</li>
</ul>
please help me out...Thanks in advance
Upvotes: 1
Views: 65
Reputation: 58462
You can use the clicks event.target
to show which child has been clicked:
<script>
function on(event) {
console.log(event.target, event.currentTarget);
// as Rob points out, there is no need to pass in this as you can access the ul from event.currentTarget
}
</script>
<ul onclick="on(event)">
<li>one</li>
<li>two</li>
</ul>
Upvotes: 5
Reputation: 147453
If you add the listener dynamically, then within the listener the element that called the listener is this and the related event object is passed as the first argument.
You can get the element that was clicked on using event.target, e.g.
function handleClick(evt) {
console.log(evt.target);
console.log(evt.currentTarget);
console.log(this);
}
//*
window.onload = function() {
document.getElementById('theUL').addEventListener('click', handleClick, false);
}
//*/
<ul id="theUL">
<li>one</li>
<li>two</li>
</ul>
Upvotes: 1
Reputation: 850
<script>
function on(event, a) {
console.log(event.target);
}
</script>
<ul onclick="on(event, this)">
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
Upvotes: 1
Reputation: 7117
Then you should call on
function in your li
tag.
<!DOCTYPE html>
<html>
<body>
<script>
function on(a) {
console.log(a);
}
</script>
<ul>
<li onclick=on(this)>one</li>
<li onclick=on(this)>two</li>
</ul>
</body>
</html>
Upvotes: 1