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

125
Views
Select id closest to id with pure javascript

<div>
  <div id="div2">TEXT</div>
</div>
<div>
  <div id="div2">TEXT</div> <!-- select this -->
</div>

<div id="div1">TEXT</div>

How to select div2 that is closest to div1

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Following w3 docs

id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.

So make sure your elements id are unique. Can switch to class instead

To select element closet to target element can use Element.closest()

The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null

<div id="div-01">Here is div-01
   <div id="div-02">Here is div-02
     <div id="div-03">Here is div-03</div>
   </div>
</div>

var el = document.getElementById('div-03');

var r1 = el.closest("#div-02");
// returns the element with the id=div-02
about 4 years ago · Juan Pablo Isaza 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!