Html example:
<div >
<div >
<div></div>
<div></div>
<div></div>
</div>
</div>
<div >
<div></div>
<div>
<div>
<div >
<div></div>
<div></div>
<div></div>
</div>
</div>
</div>
</div>
<div >
<div>
<div>
<div>
<div >
<div></div>
<div></div>
<div></div>
</div>
</div>
</div>
</div>
<div>
<div>
<div>
<div >
<div></div>
<div></div>
<div></div>
</div>
</div>
</div>
</div>
<div></div>
</div>
Desired result: div.findMe
from each "html .test tree", without using: '.findMe', '[class]' & etc
Is it possible to find the closest parent that contains more than 1 children?
- Any nesting depth
- Choosing how many children there should be, or how many more
CodePudding user response:
You can take the first parent who has enough children. Somehow:
const findMe = childsCount => $($('.test').find(`*>*:nth-child(${childsCount})`).parent().get(0));
// The first father in .test who has 3 children
findMe(3).css('background-color', 'yellow');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<div></div>
<div></div>
<div>
<div>
<div >
<div>1.1</div>
<div>1.2</div>
</div>
</div>
</div>
<div></div>
<div></div>
</div>
<div >
<div></div>
<div>
<div>
<div>
<div >
<div>2.1</div>
<div>2.2</div>
<div>2.3</div>
</div>
</div>
</div>
</div>
<div>
<div>
<div>
<div >
<div>3.1</div>
<div>3.2</div>
<div>3.3</div>
</div>
</div>
</div>
</div>
<div></div>
</div>