How can I add a custom class to every 2nd message?

Okey, there’s a huge chance I am just very stupid and can’t see the obvious but I am wondering on how to write a plugin/extension that will simply add one extra class to every 2nd .topic-body. Reason for why I need it is to add a different background color for them (and doing it via sheer CSS is pretty hard considering they are all in separate rows etc). So I can get to this result:

Right now I am using a timer based approach that I’ve seen here but it’s actually not firing every time, once in a while it fails to do so after loading next batch of posts. Which annoys me a lot.

So I’ve come to a conclusion that I need to either understand when exactly does Discourse loads new messages (aka which event causes it) or that it should be done server-side, at the render time. However I am at a loss on how to implement it, it seems I am really lacking experience with AJAX heavy development. Any advice or at least a link to some resources that could help me here would be awesome

Hi ziptofaf welcome to the forum

I’m not convinced that any class attributes need to be inserted into the DOM and I think there is a good chance that satisfactory results can be obtained purely by using the correct CSS selectors.

For example, this “works” somewhat except “small action” posts may make it a bit off from what you’re wanting. > div:nth-child(odd) {
  background-color: #bde;

Sadly it’s just as you said - small action posts will take it long way from what I am trying to accomplish.

As the different color will spread way too much to the right and it looks poorly, I’ve tried that before and my users instantly disliked it. So as much as it looks like an overkill I don’t see a way to do it via sheer CSS yet properly.

That’s just basic CSS and a result of not targeting the correct element.

“small action” posts can be excluded from the styling easily enough by specifying the class value “topic-post”, but the odd-even uses the element regardless of the class attribute :frowning2: > div.topic-post:nth-child(2n) div.topic-body {
  background-color: #bde;
} > div.topic-post:nth-child(2n+1) div.topic-body {
  background-color: #edb;


Oh my!
Thanks :stuck_out_tongue:
That’s what I get for working too much in back-end instead of front-end, I forgot about such simple things!

1 Like