To restructure an HTML list in JavaScript by making certain li elements a child of another li based on a specific character, you can iterate through the list items and use DOM manipulation methods like appendChild().
This example assumes the li elements to be nested contain a specific character (e.g., '-') at the beginning of their text content, and should be nested under the preceding li that does not have the character.
javascript
function nestListItems(ulSelector, markerChar) {
const ul = document.querySelector(ulSelector);
if (!ul) return;
// Select all direct child li elements of the ul
const items = Array.from(ul.children);
let parentItem = null;
items.forEach(item => {
// Check if the current li contains the specific character
if (item.textContent.trim().startsWith(markerChar)) {
// If a parent li has been established, move the current item into it
if (parentItem) {
// Remove the item from its current position in the DOM
ul.removeChild(item);
// Create a new nested ul if one doesn't exist in the parent
let nestedUl = parentItem.querySelector('ul');
if (!nestedUl) {
nestedUl = document.createElement('ul');
parentItem.appendChild(nestedUl);
}
// Append the current item (which is now a new node) to the nested ul
nestedUl.appendChild(item);
Array.from(nestedUl.children).forEach(itemtext => { itemtext.querySelector('a').innerHTML=itemtext.textContent.substring(2);
});
}
} else {
// If it doesn't have the marker, it becomes a potential new parent
parentItem = item;
}
});
}
// Usage: Call the function for your specific UL and marker
nestListItems('#myList', '-');