0

I want to get the href from a tag releted to that div. I'm having html structure like

    <div>
     <a>
     <button>
    </div>

Above structure in for loop, having different urls in href.

I want something like when I clicked on 1st button inside 1st div i want url in href of that div. When I clicked on 2nd div button I want url in href of 2nd div.

How do I achieve that.

Zain Ul Abidin
  • 2,467
  • 1
  • 17
  • 29

1 Answers1

0

One solution is to give the button a class and add event listner

const buttons = document.querySelectorAll('.button');
buttons.forEach(button => {
  console.log(button)
  button.addEventListener('click', (e) => {
    const button = e.target;
    const href = button.parentNode.querySelector('a').href;
    alert(href)
  })
})
<div>
     <a href="https://www.google.com">google link</a>
     <button class="button">button</button>
</div>
<div>
     <a href="https://www.facebook.com">facebook link</a>
     <button class="button">facebook</button>
</div>
<div>
     <a href="https://www.yahoo.com">yahoo link</a>
     <button class="button">yahoo</button>
</div>
Mina
  • 14,386
  • 3
  • 13
  • 26