Dynamically change an element's CSS class/attributes

Hi all, another day, another question :slight_smile:

I would like to change the attributes of an element dynamically, based on data contained in the post. For instance, I want each post in a Wordpress loop to have a title of a different colour, defined per-post.

I thought of using Wordpress Custom Fields. By storing the colour’s hex in a Custom Field, I should be able to retrieve it in a Wordpress loop bloc via the shortcode %WP_CustomField(KeyColour)%.

However, I am not sure how to apply it in any meaningful way. I can’t use shortcodes in the values of the class via the editor, and I can’t put a shortcode as the class name, as Blocs would immediately convert it to an actual class name:

I also thought of Custom Attributes, but any custom attribute that would allow me to do that automatically (like for instance class, style, etc) is reserved.

Schermata 2022-08-03 alle 22.45.44

I imagine I could create an attribute of my own, and pass it through that. But then? What do I do with it? I thought of some javascript to retrieve that attribute and modify the CSS properties, would that work?

As usual, happy to hear of other solutions entirely! Thanks.

Ok, I kinda answered myself - though I would still love ideas on how to do it better.

1: First, I add a class called .key-colour and a custom attribute to all of the elements that I need to style (for now, an H5). The custom attribute looks like this:

c = %WP_CustomField(Img1)%

This way, I know which elements I want to swap, and that custom attribute will contain the colour, which can be unique for each post/page.

2: Then I’ve put this code in the site’s header, which executes every time a page has finished loading:

<script>
window.addEventListener("load", changeTextColour);

function changeTextColour() {
	var keyColour;
	const collection = document.getElementsByClassName("key-colour");
	for (let i = 0; i < collection.length; i++) {
		keyColour = collection[i].getAttribute('c');
  		collection[i].style = "color: " + keyColour + " !important;";
	}
}
</script>

The javascript finds all elements with the .key-colour class and assigns the element a custom style using the value of the c attribute. The result:

I think there is a delay in changing that colour, but because the site has a preloader, I don’t see the colours snapping. So… it’s good? :crossed_fingers: