0

I have a construction made up of several nested <div> and <input> components.

When I focus on one of the inputs, I would like to change the background color of the first element in the hierarchy that has the class note.

The code below shows the general idea, but it works only for the first (parent) element above the focused-on input.

document.addEventListener('focusin', (event) => changeFocusColor(event))
const changeFocusColor = (event) => {
  // here comes the computation of the element to do ...style.BackgroundColor = ... on
  event.target.parentElement.style.backgroundColor = 'yellow'
}
<div>
  <div class="note">
    <input />first level
    <div>
      <input />second level
      <input />second level
    </div>
  </div>
  <div>hello</div>
</div>

Is there a clean way to say "go up in the DOM tree until you find an element with the class note and apply a style on it"?

The way I plan to do it is to iterate over element.path and check its classList until I find note there, and then apply style.background on that element.

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • 1
    So, you’re looking for [`closest`](//developer.mozilla.org/docs/Web/API/Element/closest)? – Sebastian Simon Sep 24 '21 at 14:14
  • @SebastianSimon: well, that's a clean way, to say the least :) Yes, this is exactly this. Would you be so kind and turn the comment into an answer so that I can accept it? Thanks! EDIT: ah, there is already a duplicate. – WoJ Sep 24 '21 at 14:18
  • The question’s already closed. This has been asked and answered a few times before. – Sebastian Simon Sep 24 '21 at 14:19

0 Answers0