Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
How ot select an element in the DOM hierarchy that has a specific class?

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!