JS – Can I get the next open div element – Not the sibling

Issue

Is it possible using just JS (or possibly with jQuery) to get the next open html element?

In the snippet below, if I click on any div it’ll give me the id of that div. I want it to get the next open element id, so e.g.

if I click on page123 it should give me 123efter
if I click on 123efter it should give me 13

I don’t want the next sibling within the encapsulating div, which is all I’ve managed to do so far!

document.addEventListener("click", function(event) {
console.log(event.target.id);
}
);
.efter{
min-height:20px;
}
.efter:hover{
background-color:beige;
}
<div>
  <div id="1">
    home
    <div id="1efter" class="efter"></div>
    <div id="11">
      page11
      <div id="11efter" class="efter"></div>
    </div>
    <div id="12">
      page12
      <div id="12efter" class="efter"></div>
      <div id="121">
        page121
        <div id="121efter" class="efter"></div>
      </div>
      <div id="122">
        page122
        <div id="122efter" class="efter"></div>
      </div>
      <div id="123">
        page123
        <div id="123efter" class="efter"></div>
      </div>
    </div>
    <div id="13">
      page13
      <div id="13efter" class="efter"></div>
    </div>
  </div>
</div>

Solution

I first create a flat array divs with all existing div ids. In the click event handler I then look up the clicked element’s successor id.

const divs=[...document.body.querySelectorAll("div")].map(d=>d.id);
document.addEventListener("click", function(event) {
console.log(divs[divs.indexOf(event.target.id)+1]);
}
);
.efter{
min-height:20px;
}
.efter:hover{
background-color:beige;
}
<div>
  <div id="1">
    home
    <div id="1efter" class="efter"></div>
    <div id="11">
      page11
      <div id="11efter" class="efter"></div>
    </div>
    <div id="12">
      page12
      <div id="12efter" class="efter"></div>
      <div id="121">
        page121
        <div id="121efter" class="efter"></div>
      </div>
      <div id="122">
        page122
        <div id="122efter" class="efter"></div>
      </div>
      <div id="123">
        page123
        <div id="123efter" class="efter"></div>
      </div>
    </div>
    <div id="13">
      page13
      <div id="13efter" class="efter"></div>
    </div>
  </div>
</div>

Answered By – Carsten Massmann

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.