-1

<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

1 Answers1

1

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
nart
  • 1,508
  • 2
  • 11
  • 24