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

184
Views
Get closest ancestor by partial class with JS

I need to get the closest ancestor by class, byt I need to use a partial class. For instance:

<div class="parent-1">
   <div class="child"></div>
</div>

I'd like to do somenthing like that: document.getElementsByClassName('child')[0].closest('.parent')

This would return null, since the parent's class name is parent-1. But is there a way in which I could get the parent using just the partial class name?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Like this

const parent = document.querySelector(".child").closest("div[class^=parent]");
console.log(parent.className)
<div class="parent-1">
   <div class="child"></div>
</div>

about 4 years ago · Santiago Trujillo Report
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!