0

How do I turn this line of jQuery:

var newFont = jQuery('h1').css('font-family');

into modern JS. Thought something like this would work:

let newFont = document.querySelectorAll('h1').style.fontFamily = "Montserrat, Roboto, Helvetica Neue, Arial, sans-serif";

but instead get error TypeError: Cannot set property 'fontFamily' of undefined

Joe Spinelli
  • 105
  • 1
  • 11
  • 1
    In short, use `document.querySelector` for one element, `querySelectorAll` for multiple. There is no bulk update methods like in jQuery; you can use something like `querySelectorAll('h1').forEach(element => element.style.fontFamily = '...')` to update multiple. – Jacob Jun 25 '20 at 19:16
  • 1
    That's because `querySelectorAll` will return an iterator. (You can think of it as a array, although it is not). You must cycle through the elements of the iterator and apply `style.fon...` to each element. jQuery functions return especial objects that allow you to apply methods to all elements of the query result calling it just once. The same doesn't happen in plain javascript. – Pedro Lima Jun 25 '20 at 19:16
  • Thanks guys! For some reason, now I get `TypeError: el.style.fontFamily is not a function` when I do that. Which I'm confused about b/c it seems like its selecting the correct and same h1 elements as the jQuery code does. – Joe Spinelli Jun 25 '20 at 19:32
  • 1
    But it is really not a function, it is a property. You had this bit right in your exemple. `...style.fontFamily = "Montserrat, Roboto, Helvetica Neue, Arial, sans-serif";` – Pedro Lima Jun 25 '20 at 19:34
  • Woww duh smh I was doing it completely wrong haha thanks for your help! – Joe Spinelli Jun 25 '20 at 19:47

0 Answers0