Change font with Javascript

Asked

Viewed 60 times

-1

I need to change the source of a system, I don’t have access to HTML, only via Google Tagmanager, so I need to change the DOM with JS.

I didn’t succeed, what’s the best way to do it?

  var a = document.getElementsByTagName("head")[0];
  var body1 = document.getElementByTagName("body");
  newFont = document.createElement("link");
  newFont.href = "https://fonts.googleapis.com/css?family=Comfortaa";
  body1.appendChild(a);
  a.appendChild(newFont);
.body{
 	font-family: 'Comfortaa', cursive;
 }

  • Did not fail to add newFont in a?

  • Yes, I just didn’t put in the example, but anyway it didn’t work.

  • 2

    Then edit the question and make an example that reproduces exactly what you did. Other than that, there is an element that has the class body?

  • Yes, I added the full code in the example.

1 answer

3


Just add the value of rel of its element <link> and fix the CSS as it is using .body instead of body.

const head = document.getElementsByTagName('head')[0];
const link = document.createElement('link');

link.rel = 'stylesheet';
link.href = 'https://fonts.googleapis.com/css?family=Comfortaa&display=swap';

head.appendChild(link);
body {
  font-family: 'Comfortaa', cursive;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque aliquam condimentum mi. Vestibulum dolor nulla, maximus et nulla vitae, tincidunt pharetra velit. Phasellus et congue lectus. Nam pretium, nisi varius interdum lobortis, felis lorem venenatis velit, eu tristique mauris ex et tortor. Aenean euismod tincidunt ligula id venenatis. Vestibulum faucibus est sed massa tempor, a luctus libero mattis. Vestibulum dapibus nulla justo, et hendrerit leo maximus non. Mauris commodo nisl eu sapien efficitur blandit. Vivamus egestas velit velit, porta maximus erat tincidunt quis. Sed id pharetra tellus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lobortis semper congue.</p>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.