简体   繁体   中英

Adding random fonts to each element of class

Been trying to make it so that each div with the class .book gets allocated a random font from an array. This is my code so far

var fonts = ['Gloria Hallelujah', 'Sedgwick Ave', 'Gochi Hand', 'Patrick Hand', 'Kalam', 'Rock Salt', 'Neucha', 'Caveat Brush', 'Schoolbell'];
var randomfont = fonts[Math.floor(Math.random() * fonts.length)];
$(".book").style.fontFamily = randomfont; 

The error I am getting is: Uncaught TypeError: Cannot set property 'fontFamily' of undefined

Anyone know what I am doing wrong?

$(".book") returns a jquery array. eg to set the first you would use:

$(".book")[0].style.fontFamily = 

You need to loop through $(".book") to get the DOM elements:

$(".book").each(function() {
    var randomfont = fonts[Math.floor(Math.random() * fonts.length)];
    this.style.fontFamily = randomfont; 
});

(unless you meant to set them all to the same font, in which case set randomfont outside the loop).

That's because you are trying to set the fontFamily directly on the jQuery object instead of the DOM element.

Either use jQuery's css method or use get / array selector to retrieve the DOM element.

On the other hand you want to do that on each element, so you need to use each like this:

 //const fonts = ['Gloria Hallelujah', 'Sedgwick Ave', 'Gochi Hand', 'Patrick Hand', 'Kalam', 'Rock Salt', 'Neucha', 'Caveat Brush', 'Schoolbell']; const fonts = ['Helvetica', 'Arial', 'Verdana', 'Courier', 'Courier New']; $('.book').each(function(item) { const randomfont = fonts[Math.floor(Math.random() * fonts.length)]; this.style.fontFamily = randomfont; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="book">Test 1</div> <div class="book">Test 2</div> <div class="book">Test 3</div> <div class="book">Test 4</div> <div class="book">Test 5</div> <div class="book">Test 6</div> 

hope this will help. just call the id using the document.getElementById('') and then set the font value.

var fonts = ['Impact,Charcoal,sans-serif', 'Sedgwick Ave', ' Helvetica', 'Patrick Hand', 'Kalam', 'Rock Salt', 'Neucha', 'Caveat Brush', 'Schoolbell'];
var randomfont = fonts[Math.floor(Math.random() * fonts.length)];
alert(randomfont);
var val=document.getElementById("book").style.fontFamily = randomfont;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM