I have a list that i want to append another list on certain conditions.
The structure looks like this:
<ul class="menu">
<li class="list-1"><ul class="ul-1"></ul></li>
<li class="list-2"><ul class="ul-2"></ul></li>
<li class="list-3"><ul class="ul-3"></ul></li>
<li class="list-4 empty-list"></li>
<li class="list-5"><ul class="ul-5"></ul></li>
</ul>
I want the list-4 empty-list, to be inside the list before it. So in this case,inside list-3, if the list is empty. I have made a check to check if lists are empty, thats why the list-4 has a class callled empty-list.
Can it be done with javascript? I have had trouble researching to a solution, also because i an not 100% sure how to describe it.
Thanks
I tried something like this:
document.addEventListener('DOMContentLoaded', function () {
var listItems = document.querySelectorAll('.list');
listItems.forEach(function (listItem, index) {
var nextSibling = listItem.nextElementSibling;
if (nextSibling && nextSibling.classList.contains('list-')) {
var emptyList = listItem.querySelector('.empty-list');
if (emptyList) {
nextSibling.appendChild(emptyList);
}
}
});
});
I am still new to this sort of coding, so tried my best.
To do what you describe, you can:
.empty-listlielement.document.querySelectorcan do that for you.liin front of it, and then find the firstulinside it.previousElementSiblingis good for getting the previousli(since there can't be anything else in aul), and the element-specific version ofquerySelectoris useful for finding the firstulwithin it..children.length === 0..empty-listelement into it viaappendChildas you have in your question (orappend).Here's an example: