practical
practical

Reputation: 79

Changing the font of certain elements on refresh, site wide, using Javascript

I am trying to as the title suggests, randomise the typeface of my h1 titles throughout the site. All of these are assigned an individual ID using php count so they take the format project-title-1, project-title-2 etc.

I have repurposed this code from a similar question I found on here but tried to apply it so it works on multiple elements.

Currently, if I remove the All from querySelector it works on the first element on the page but no others, so the code kind of works but there is a problem somewhere.

Any insight would be greatly appreciated! Cheers

var fonts = ['hauser', 'helvetica', 'times'];
var rand = fonts[Math.floor(Math.random() * fonts.length)];
console.log(rand);

var bodyElement = document.querySelectorAll("[id^='project-title']");
bodyElement.className = rand;

Basic working example here: https://jsfiddle.net/psvu78aq/2/

Upvotes: 0

Views: 116

Answers (2)

Anthony BONNIER
Anthony BONNIER

Reputation: 355

Your code has some problems :

  • You only call the random fonts array once at the beginning
  • As 31piy said, you have to loop over the elements returned by the querySelectorAll
  • In your example on jsfiddle, you named the class 'Arial' with an uppercase 'A' but put a lowercase 'a' in the array, which did not work.

Here is a snippet which seems to work :

const fonts = ['Arial', 'helvetica', 'times'];

function getRand() {
 return fonts[Math.floor(Math.random() * fonts.length)];
}

const bodyElements = document.querySelectorAll("[id^='project-title']");
for (let bodyEl of bodyElements) {
    bodyEl.className = getRand();
}

https://jsfiddle.net/psvu78aq/9/

Upvotes: 0

31piy
31piy

Reputation: 23859

An ideal approach would be to apply the class on a parent element so that it applies on all the children of it.

But, just to fix your code, the following should work:

var bodyElement = document.querySelectorAll("[id^='project-title']");
bodyElement.forEach(elem => elem.classList.add(rand));

The reason is (as you already know), document.querySelectorAll returns a collection of elements. So you need to go through each of it and then individually apply the class.

Upvotes: 1

Related Questions