-1

I am struggling to get the parent of button when it is clicked. This is my HTML structure:

<p><button class="remove">x</button> Hamlet<input value="5"></p>

I don't want to use the ID in button because I have many of the same buttons. Any help is appreciated. Thanks!!!

unitSphere
  • 241
  • 3
  • 17
  • The problem is solved in JS, please show the JS code related to the event handler of the button. – Teemu Jan 31 '20 at 08:54
  • See [here](https://stackoverflow.com/questions/59054548/js-get-the-clicked-element-with-event-target) to get the button, then [here](https://stackoverflow.com/questions/6856871/getting-the-parent-div-of-element) to get its parent. – T.J. Crowder Jan 31 '20 at 08:56

2 Answers2

2

Like this? Note I delegate from a container

document.getElementById("container").addEventListener("click", function(e) {
  let tgt = e.target;
  if (tgt.classList.contains("remove")) tgt.closest("p").remove();
})
<div id="container">
  <p><button class="remove">x</button> Hamlet<input value="1"></p>
  <p><button class="remove">x</button> Ophelia<input value="2"></p>
  <p><button class="remove">x</button> Polonius<input value="3"></p>
</div>

For browser that doe not like closest you can use tgt.parentElement.remove()

mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

Maybe consider adding a universal click event to all buttons.

const onClickButton = function () {
  // The parent element
  const parent = this.parentElement;
  parent.style.backgroundColor = 'red';
};

[...document.getElementsByTagName('button')].forEach(button => button.addEventListener('click', onClickButton));
<p>
  <button class="remove">x</button>
  Hamlet1
  <input value="5">
</p>

<p>
  <button class="remove">x</button>
  Hamlet2
  <input value="5">
</p>

<p>
  <button class="remove">x</button>
  Hamlet3
  <input value="5">
</p>
Hao Wu
  • 17,573
  • 6
  • 28
  • 60