I am trying to add a class to a js generated paragraph, but it does not work. I have also tried to add style directly to the DOM element, but neither does this work. What am I doing wrong?
var dataCurent = new Date();
var minut = dataCurent.getMinutes();
var vector = [1, 2, 3, 4, 5];
function ParagrafNou() {
for (let i = 0; i < Math.max(10, minut); i ) {
var index = Math.random(vector);
var paragraf = document.createElement('p');
var continut = document.createTextNode('Ilie Andrei-Virgil ');
paragraf.style.fontSize = 'xxx-large';
if (index == 1)
paragraf.classList.add('clasa1');
if (index == 2)
paragraf.classList.add('clasa2');
if (index == 3)
paragraf.classList.add('clasa3');
if (index == 4)
paragraf.classList.add('clasa4');
if (index == 5)
paragraf.classList.add('clasa5');
document.body.appendChild(paragraf.appendChild(continut));
}
}
ParagrafNou()
.clasa1 {
color: red;
}
.clasa2 {
color: blue;
}
.clasa3 {
color: green;
}
.clasa4 {
color: black;
}
.clasa5 {
color: orange;
}
CodePudding user response:
- You need to add the text to the paragraph and then add the paragraph to the body
- Your index was not an int
- Your random also needed fixing
var dataCurent = new Date();
var minut = dataCurent.getMinutes();
var vector = [1, 2, 3, 4, 5];
function ParagrafNou() {
for (let i = 0; i < Math.max(10, minut); i ) {
var index = vector[Math.floor(Math.random() * vector.length)];
var paragraf = document.createElement('p');
var continut = document.createTextNode('Ilie Andrei-Virgil ');
paragraf.style.fontSize = 'xxx-large';
if (index == 1)
paragraf.classList.add('clasa1');
if (index == 2)
paragraf.classList.add('clasa2');
if (index == 3)
paragraf.classList.add('clasa3');
if (index == 4)
paragraf.classList.add('clasa4');
if (index == 5)
paragraf.classList.add('clasa5');
paragraf.appendChild(continut)
document.body.appendChild(paragraf);
}
}
ParagrafNou()
.clasa1 {
color: red;
}
.clasa2 {
color: blue;
}
.clasa3 {
color: green;
}
.clasa4 {
color: black;
}
.clasa5 {
color: orange;
}
CodePudding user response:
Math.random()
will return a value between 0 inclusive but not 1 which is not the index you are using in the next if statements.
In order to get a random index from vector
array, you should use:
var index = Math.floor(Math.random() * vector.length);