DEV Community

Beey
Beey

Posted on

Connecting CSS to JS(CSS basics part 4/60)

How to connect CSS to JS

Cascading Style Sheets(CSS) is not just limited to external files, you can use it directly in a JS file.

An example of this would be changing the color of a text with the id of 'title':


let title = document.getElementById('title');

title.style = 'color: blue;'

Enter fullscreen mode Exit fullscreen mode

Going deeper with Linking CSS to JS

Did you know you can go deeper when linking CSS to JS?

You can edit a specific style:


let title = document.getElementById('title');

title.style.color = 'blue';

Enter fullscreen mode Exit fullscreen mode

You can even turn styling into a function!


let title = document.getElementById('title');

function Style(HtmlElement, CssStyle) {
  HtmlElement.style = CssStyle
}

Style(title, 'color: blue;');

Enter fullscreen mode Exit fullscreen mode

Same applies to specific styling


let title = document.getElementById('title');

function StyleColor(HtmlElement, Value) {
  HtmlElement.style.color = Value;
}

StyleColor(title, 'blue');

Enter fullscreen mode Exit fullscreen mode

thats how you link or connect CSS to JS!

Conclusion

In the next part we will explore using inline CSS and writing CSS code in html with <style>.

Top comments (1)

Collapse
 
crdtcto profile image
Kane Lim

Good beginner-friendly introduction. One small thing I’d emphasize is that JavaScript isn’t really “connecting CSS to JS” so much as using the DOM API to change an element’s inline styles.

For larger projects, I’d recommend introducing classList early rather than setting style directly:

title.classList.add("active");

Then keep the actual styling in CSS. It makes the JS responsible for behavior and the CSS responsible for presentation, which scales much better as the UI gets more complex.

The progression from direct styles → functions → CSS classes is a useful path for beginners.