I am writing a userscript for Greasemonkey/Tampermonkey (and learning JS in the process). It is for a discussion forum (/bulletin board), where each post is assigned one of six possible styles based on some criteria. The post contains a div with the username, a div with a timestamp, a div with avatar and user info, and a div for the content itself (which may or may not include a quote div).
For simplicity's sake, let's just call the styles red, blue, green, yellow, black and white. (Note: it is not just color – each style has its own distinct value of "everything", even margins, paddings and other layout.)
Then, each post is styled with a call to a style-changing function, for example makeRed(post) or makeGreen(post).
Then, each of those functions look something like this:
const makeRed = post => {
let author = post.querySelector(".author");
author.style.fontSize = "...";
author.style.fontFamily = "...";
author.style.backgroundColor = "...";
author.style.padding = "...";
author.style.borderRadius = "...";
author.style.margin = "...";
author.style.flex = "...";
// ...
let date = post.querySelector(".date");
date.style.fontFamily = "...";
date.style.fontSize = "...";
date.style.color = "...";
date.style.margin = "...";
date.style.flex = "...";
// ...
let avatarInfo = post.querySelector(".infoBox");
avatarInfo.style.backgroundColor = "...";
avatarInfo.style.fontSize = "...";
// ...
let content = post.querySelector(".content");
content.style.borderColor = "...";
content.style.backgroundImage = "...";
// ...
let quote = content.querySelector(".quote");
if (quote) {
// Lots of quote styling here
} else {
// Lots of quote-less styling here
}
}
Each of these functions contain significantly more lines of code in a similar fashion, I just cut them out of this question to save some space.
So, to the question:
Is there any way to write this more concisely/elegantly?
I guess it's hard to avoid having a line for each style property, but at least in CSS it looks a bit nicer, IMO. Would it be a better practice to create a CSS-file and somehow import it with JavaScript (how?), or is this long list of element.style.property = "..." actually the way to go? Or is there a better way? How would you do it?
Also, I'm brand new to JS, so if you have any other advice (related to my code or not), please let me know!
Thank you very much! :-)
Edit:
I was asked to include the HTML structure. A typical post is simply something like this:
<div class="post">
<div class="author">Author McAuthorson</div>
<div class="date">2021.01.10 01:23</div>
<div class="infoBox">
<div class="avatar"><img src="..." /></div>
<div class="userinfo">User info here</div>
</div>
<div class="content">
<div class="quote">Some quote by some guy here</div>
Some original text by McAuthorson here.
</div>
</div>