Skip to content
Advertisement

How do you get the wider context HTML that wraps a given selector code in jQuery or Cheerio js?

How do you get the entire HTML of h1 + ul > li > details > summary + p only if it has that structure? i.e. it wouldn’t get the HTML of a ul tag element if it doesn’t have a nested li, details etc.

h1+ul>li>details>summary+p
<div>
  <h1>T1</h1>
  <ul class="toggle">
    <li>
      <details>
        <summary><strong>Q1</strong></summary>
        <p>Answer1</p>
      </details>
    </li>
  </ul>
  <h1>T2</h1>
  <ul class="toggle">
    <li>
     <details>
       <summary>Q2</summary>
       <strong>Answer2</strong>
     </details>
    </li>
  </ul>
</div>

Advertisement

Answer

Like this?

const $collection = $("ul.toggle")
  .has("li>details>summary+p")
  .prev()
  .addBack()
  .addClass("red")
  
console.log($collection.text())  
.red { background-color:red }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <h1>T1</h1>
  <ul class="toggle">
    <li>
      <details>
        <summary><strong>Q1</strong></summary>
        <p>Answer1</p>
      </details>
    </li>
  </ul>
  <h1>T2</h1>
  <ul class="toggle">
    <li>
     <details>
       <summary>Q2</summary>
       <strong>Answer2</strong>
     </details>
    </li>
  </ul>
</div>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement