Извините, если на этот вопрос уже был дан ответ, но я не смог найти решение. Я новичок в разработке в js и немного застрял в коде.
По сути, я пытаюсь изменить идентификатор div каждый раз при загрузке окна.
Мне удалось случайным образом получить значение из массива при каждой загрузке, но мне не удалось назначить его моему элементу в качестве идентификатора (с помощью атрибута set).
Вот код:
// on load change type
window.onload = changeType;
// array of styles
let styles = ['style1', 'style2', 'style3', 'style4'];
// shuffle array
function shuffle(styles) {
var ctr = styles.length,
temp, index;
// while there are elements in array
while (ctr > 0) {
// pick random index
index = Math.floor(Math.random() * ctr);
// decrease ctr by one
ctr--;
// swap last element and ctr
temp = styles[ctr];
styles[ctr] = styles[index];
styles[index] = temp;
}
// return array
return styles;
}
// To avoid having them same value twice
// shuffle array
let shuffleStyle = shuffle(styles);
// pick random value
let randomStyle = styles[Math.floor(Math.random() * styles.length)];
// test
console.log(randomStyle);
// value to string
let randomFinal = randomStyle.toString();
//test
console.log(randomFinal);
// replace id by random array value
function changeType() {
document.getElementById("style").setAttribute("id", randomFinal);
}