I have the following html code:
<div class="account-type">
<h3>Assets</h3>
<ul> ...lots of data in here... </ul>
<div class="account-type">
<h3>Liabilities</h3>
<ul> .... lots of elements in here... </ul>
How do I isolate the div tag with the class of "account-type" that is the direct parent of the h3 tag with the text "Liabilities"? I need to isolate it and then loop through all of the elements in it's ul tags.
Assuming <ul>
should come after <h3>
, you can use this combination:
function getItemByTitle( title ){ return $(`h3:contains("${title}")`).next('ul').children() } var listItems = getItemByTitle("Liabilities") console.log(listItems.length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="account-type"> <h3>Assets</h3> <ul></ul> </div> <div class="account-type"> <h3>Liabilities</h3> <ul> <li>1</li> <li>2</li> </ul> </div>
There is no text match in DOM so need to select all the elements, look to see if the text matches. If it does select the parent.
const h3 = Array.from(document.querySelectorAll(".account-type > h3")).find(elem => elem.textContent.trim() === 'Liabilities'); console.log(h3) const div = h3.closest(".account-type"); console.log(div); const lis = div.querySelectorAll("ul li"); console.log(lis.length); // or console.log(h3.nextElementSibling.children)
<div class="account-type"> <h3>Assets</h3> <ul></ul> </div> <div class="account-type"> <h3>Liabilities</h3> <ul> <li>a</li> <li>b</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.