How do I get the rank of the button

<section>
    <div data-index='1'>
        <p>First</p>
        <button  onclick='showRank()'>First</button>
    </div>
    <div data-index="2">
            <p>Second</p>
        <button onclick='showRank()'>Second</button>
    </div>
    <div data-index="3">
            <p>Third</p>
        <button onclick='showRank()'>Third</button>
    </div>
</section>
function showRank(){
 // I don't know what to do now 
}

When I click any one of the buttons I want to console.log() the div in which the button is.
For example :
input -: Clicked the button 'First'
output -:

  <div data-index='1'>
     <p>First</p>
     <button  onclick='showRank()'>First</button>
  </div>

@ved08 Clicking the button you get the event as params of your function.
function showRank(event){ console.log(event)}
You can also give a value to your tag button or an id, then in the function access to it with event.target.value or event.target.id. I suggest to read some docs about events on MDN

You can get to the <p> element using previousElementSibling.

function showRank() {
  console.log(event.target.previousElementSibling.textContent)
}

Just as a note. If you add event as a parameter to the handler function you need to pass the event to the function call showRank(event), otherwise it will be undefined inside the function as you are overwriting the event pass to the handler with your own parameter.

// Overwriting the event
<button onclick='showRank()'>Third</button>

function showRank(event) {
  // TypeError: Cannot read property 'target' of undefined
  console.log(event.target)
}

// Explicitly passing event
<button onclick='showRank(event)'>Third</button>

function showRank(event) {
  // the event.target
  console.log(event.target)
}

// Implicit event available in the handler
<button onclick='showRank()'>Third</button>

function showRank() {
  // the event.target
  console.log(event.target)
}
1 Like

@lasjorg Thanks for your answer. But cant we get the <div> as output

You mean the div container the button is inside?

function showRank() {
  console.log(event.target.parentElement)
}

Yes… thanks for your reply…this is working