Abhishek
Abhishek

Reputation: 351

how to select html element objects

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

Answers (4)

Pete
Pete

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

RobG
RobG

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

Liar Рonest
Liar Рonest

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

Upvotes: 1

Sankar
Sankar

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

Related Questions