I’m looking to craft a creative workaround to generate “Topic” tags as list items for CMS Collection items, without having to nest another collection list (thus getting around nesting limit), using Javascript. I feel like I’m really close and am just missing something obvious, so I’d really appreciate if someone could help me out, and I hope this could be a useful solution for others to consider!
I have the CMS item’s Topics stored in a plain text field as a comma separated list, ie. ‘Topic1,Topic2,Topic3’
The desired output is to create a <ul> and append a <li> for each item in an array that’s been created of out of the comma-separated string using the split method.
<ul>
<li>Topic1</li>
<li>Topic2</li>
<li>Topic3</li>
</ul>
Here’s the code I have so far, which is not working…
// in a custom code embed, split a text string into an array
let topicsString = 'text,string,from,CMS,field';
let topicsArray = topicsString.split(',');
console.log(topicsArray);
// so far, so good
// now, create a new <ul> and set its ID
let ul = document.createElement("ul");
ul.setAttribute("id", "topics-list");
// finally, loop through the array and create a <li> inside the <ul> for each
for (let i of topicsArray) {
let li = document.createElement("li");
li.innerHTML = i;
ul.appendChild(li); }
Bonus Points if you can tell me how to add classes to each of the <li>s so that I can then style them, too! So that would be:
<ul class="ul-class">
<li class="li-class">Topic1</li>
<li class="li-class">Topic2</li>
<li class="li-class">Topic3</li>
</ul>