Search code examples
javascripthtmlcssweb-scrapingnode-html-parser

How do I select all siblings before an element with JavaScript?


I'm using node-html-parser to parse a document. The structure is below:

<div class="content">
  <div class="item">1</div>
  <div
    style="
      margin-top: 20px;
      display: flex;
      flex-direction: row;
      align-items: center;
      font-family: PingFangSC;
    "
  >
    DIVIDER LOLZ
  </div>
  <div class="item">2</div>
  <div class="item">3</div>
</div>

I want to get all the elements before the divider, i.e., the first .item in the document.

Note: this is not a duplicate of How do I select previous siblings before specific class?, which only styles the elements.


Solution

  • I tweaked your code a bit, but the idea remains the same.
    You might use selector .item:not(.divider ~ .item)

    const items_before_divider = document.querySelectorAll('.content > .item:not(.divider~.item)');
    
    items_before_divider.forEach(item => console.log(item.outerHTML))
    .divider {margin-top: 20px;
          display: flex;
          flex-direction: row;
          align-items: center;
          font-family: PingFangSC}
    <div class="content">
      <div class="item">0</div>
      <div class="item">1</div>
      <div class="divider">DIVIDER LOLZ</div>
      <div class="item">2</div>
      <div class="item">3</div>
    </div>