The fonts I wanted to use needed a few extra steps in order to work since they needed to be imported from somewhere.
Here's how I was able to make it work.
element.style.fontFamily = "Lato";
However, if we don't import the font this isn't going to do anything!
We can create and add DOM elements like divs and spans, but we aren't limited to just structural elements.
We can add
<style> elements too!
Here's what it could look like:
var link = document.createElement('link'); link.setAttribute('rel', 'stylesheet'); link.setAttribute('type', 'text/css'); link.setAttribute('href', 'https://fonts.googleapis.com/css?family=Lato:300,400,700'); document.head.appendChild(link);
How does this work?
First, we create the element. We can use
document.createElement('link') to create the
<link> element we talked about earlier.
Next we need to add a few attributes to specify the attributes and where to import the font from.
Let's declare this as a stylesheet by setting the rel attribute to stylesheet.
Then we specify the type as CSS.
This will let us link to the font family that we want to import for our text.
Last, we need to add this entire element to the DOM.
Typically, we import fonts and stylesheets in the head section of our page, so I'll append this new element to the
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Lato:300,400,700" />
And then any element that needs this font will be able to use it!
It looks like this:
var element = document.getElementById('banner-title') element.style.fontFamily = "Lato";
This guide was inspired by a set of features I'm building for UserSurge.
It's one of a few projects I'm building and is full of new interesting technical challenges.
Subscribe to my mailing list to stay up to date on interesting things I overcome and share with everyone.
You can reach me on Twitter if you have any questions or want to connect!