JavaScript/jQuery Text Methods inside CMS Item Embeds

I have a CMS collection with a field called “Complexity” which contains an rating (integer) related to that collection item. I’m trying to use a quick formula to turn those integers into text, a number of stars correlating to the rating stored in the field - and display it for each CMS item listed on the page.

E.g. if Complexity = 3 then the desired output would be ⭐⭐⭐

I figured a simple script like this would work, but where I’m getting lost is that the method isn’t writing the result to the page, just computing the method in memory — I know that in Javascript or JQuery, normally one would select a DOM element and then use the text method on that, but that seems convoluted to assign $IDs to every CMS item… or could I do it with a class?

Is there a way to just output the computed text in place, which would be the div where each CMS item’s embed element is nested?

Hi @shawncarrie,

Would tying it to the ID of field/div where you want to place it and setting the innerHTML work? Like so:

document.querySelector('#id').innerHTML = "⭐".repeat(3)

Let me know! Keen to work through this one with you

I don’t think that would work, because I’m using this in collection lists, so I’d end up with duplicate IDs on the page. Here’s a read-only link, I’m referring to the page ‘Library’.

I suppose a workaround would be to use the Embed to create a divs with IDs such as #this-complexity, #that-complexity, #third-complexity (according to their item slugs) and then select them — however that seems clunky.

But I think this gets me closer to what I’m looking for: instead of fussing with creating and then selecting IDs, could I use a method like createElement to just create the text in place? All I need is for there to be a certain number of starts that corresponds to the collection item (which I already have access to in the embed.)

Hey @shawncarrie , I built a ratings tool just for this purpose.
The stars are SVG so they can be easily sized and colored, and it allows fractional stars too, like 3.5.

image