Warm tip: This article is reproduced from stackoverflow.com, please click
html javascript

Getting the parent of button without ID in Javascript

发布于 2020-03-27 15:43:52

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!!!

Questioner
Rustam
Viewed
17
Hao Wu 2020-01-31 17:03

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>