简体   繁体   中英

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? ie 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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM