Search code examples
javascripthtmlcssfonts

use document.body.style to @import js/css (JS/CSS help)


I don't know how to use document.body.style to use @import in JavaScript.

it should work like this in jsfiddle.com: "document.body.style.import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');" but it highlights as "not good enough"

It's for a function listing it below

function font(fontData){
    var font = fontData.font;
  var applyFont = fontData.text;
  document.body.style.import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
  document.getElementById(applyFont).style.fontFamily = ;
}

I want to use it like this:

font({
   "font": "ubuntu",
   "text": "h1" // should apply to h1
})

Solution

  • Here's updated code that works

    function addFont(font, fontName){
      const link = document.createElement("link")
      link.href = font;
      link.rel = "stylesheet"
      document.body.insertBefore(link, target);
      console.log(link)
      document.body.style.fontFamily = fontName;
    }
    addFont("https://fonts.googleapis.com/css2?family=Roboto&display=swap", "'Roboto', sans-serif")