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.
2
Answers
It seems like you’re on the right track with your attempt. However, there are a couple of issues in your code that need to be addressed.
Let’s correct them:
1.Your query selector .list should be .menu > li, because you’re targeting
2.In your if condition, you’re checking nextSibling.classList.contains(‘list-‘). Instead, you should check for empty-list class.
Here’s the corrected version of your JavaScript code:
});
This code will move any empty list (identified by the presence of the class empty-list) inside the previous list item. Make sure that your HTML structure is correct and matches your JavaScript logic.
To do what you describe, you can:
.empty-list
li
element.document.querySelector
can do that for you.li
in front of it, and then find the firstul
inside it.previousElementSibling
is good for getting the previousli
(since there can’t be anything else in aul
), and the element-specific version ofquerySelector
is useful for finding the firstul
within it..children.length === 0
..empty-list
element into it viaappendChild
as you have in your question (orappend
).Here’s an example: