wrap li items within span in javascript

Assuming you have an ordered or unordered list (ul or ol) with li items that you want to wrap within span elements using JavaScript, you can use the following code:

index.tsx
// get the list element
const list = document.querySelector('ul');

// get all the li items within the list
const listItems = list.querySelectorAll('li');

// loop through each li item
listItems.forEach(item => {
  // create a new span element
  const span = document.createElement('span');
  
  // move the contents of the li item into the new span element
  span.innerHTML = item.innerHTML;
  
  // replace the li item with the new span element
  item.parentNode.replaceChild(span, item);
});
495 chars
18 lines

This code will loop through each li item in the list, create a new span element, move the contents of the li item into the new span element, and replace the li item with the new span element.

related categories

gistlibby LogSnag