1

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

4 Answers 4

5

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>

Sign up to request clarification or add additional context in comments.

2 Comments

You need pass event with on(event,this) .In Firefox not support without pass event
There is no need to pass this if it's not used. The UL is available as event.currentTarget. ;-)
1

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>

Comments

1

<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>
Thank you

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.