Skip to content

Instantly share code, notes, and snippets.

@ilyasudakov
Last active May 13, 2023 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilyasudakov/ca9dfa57b2dc6e4f5ee0fef64b7e5e24 to your computer and use it in GitHub Desktop.
Save ilyasudakov/ca9dfa57b2dc6e4f5ee0fef64b7e5e24 to your computer and use it in GitHub Desktop.
Parser for nested Unordered & Ordered lists inside Rich Text element. Add this code before </body> in page settings. More info here: https://discourse.webflow.com/t/nested-lists-in-rich-text-element-custom-vanilla-javascript-solution-for-unordered-ordered-lists/242024/1
/*
# Example of how to use nested lists in Rich Text element in Webflow Editor
## Unordered list
* Step 1.
* Step 2.
* ~Step 2.1
* ~~Step 2.1.1
* ~Step 2.2
* Step 3.
## Ordered list
1. Step 1.
2. Step 2.
3. ~Step 2.1
4. ~~Step 2.1.1
5. ~Step 2.2
6. Step 3.
*/
(() => {
const unordered_lists = document.querySelectorAll(".w-richtext > ul");
const ordered_lists = document.querySelectorAll(".w-richtext > ol");
function replaceChild(newItem, oldItem) {
oldItem.parentNode.replaceChild(newItem, oldItem);
newItem.appendChild(oldItem);
}
function createUnorderedList(item) {
const list = document.createElement("ul");
list.style = "margin-bottom: 0;";
replaceChild(list, item);
}
function createOrderedList(item, start) {
const list = document.createElement("ol");
list.style = "margin-bottom: 0;";
list.type = "a";
list.start = start;
replaceChild(list, item);
}
function parseUnorderedList(item) {
const nest_level = item.innerText.split("~").length - 1;
item.innerHTML = item.innerHTML.replaceAll("~", "");
if (nest_level === 0) return;
new Array(nest_level).fill(0).map(() => createUnorderedList(item));
}
for (const list of unordered_lists) {
for (const item of list.children) {
parseUnorderedList(item);
}
}
function parseOrderedList(item, queue) {
const nest_level = item.innerText.split("~").length;
item.innerHTML = item.innerHTML.replaceAll("~", "");
if (nest_level === queue.length) {
queue[nest_level - 1]++;
}
if (nest_level > queue.length) {
queue[queue.length] = 1;
}
if (nest_level < queue.length) {
queue.splice(nest_level);
queue[nest_level - 1]++;
}
if (queue.length > 1) {
new Array(queue.length - 1)
.fill(0)
.map(() => createOrderedList(item, queue[queue.length - 1]));
}
}
let queue = [0];
for (const list of ordered_lists) {
for (const item of list.children) {
parseOrderedList(item, queue);
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment