Привет!
как добавить
document.getElementByClassName к следущему коду: Учитывать нужно чтобы было и
documen.getElementById и
document.getElementByClassName Спасибо!
<div class="themes">
<button class="gray" data-theme="gray">GRAY</button>
<button class="red" data-theme="red">RED</button>
<button class="green" data-theme="green">GREEN</button>
<button class="blue" data-theme="blue">BLUE</button>
<button class="unknown" data-theme="unknown">unknown</button>
</div>
<div id="opops">Testing</div>
<div id="opopops">Testing</div>
const themes = {
gray: 'theme--gray',
red: 'theme--red',
green: 'theme--green',
blue: 'theme--blue'
}
const themeElements = [
document.getElementById('opops'),
document.getElementById('opopops'),
];
const themeFromStorage = localStorage.getItem('theme');
const defaultTheme = themes[themeFromStorage] || themes.gray;
themeElements.forEach(element => element.classList.add(defaultTheme));
const themeSwitchers = document.querySelectorAll('[data-theme]');
for (const switcher of themeSwitchers)
switcher.addEventListener('click', switchThemeHandle);
function switchThemeHandle(e) {
const { theme } = e.target.dataset;
if (!Object.keys(themes).includes(theme)) {
console.error('Ошибка смены темы. Тема не найдена.');
return;
}
themeElements.forEach(element => {
element.className = element.className.replace(/([theme\-\-]+[a-z]+)/, '');
element.classList.add(themes[theme]);
});
localStorage.setItem('theme', theme);
}
.themes {
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
display: flex;
}
.themes > * {
margin: 0 10px;
}
.themes button {
padding: 12px 24px;
border-width: 1px;
border-style: solid;
outline: none;
color: #fff;
cursor: pointer;
}
.themes .gray { background-color: #95a5a6; border-color: #7f8c8d; }
.themes .red { background-color: #e74c3c; border-color: #c0392b; }
.themes .green { background-color: #2ecc71; border-color: #27ae60; }
.themes .blue { background-color: #3498db; border-color: #2980b9; }
.themes .unknown { background-color: #9b59b6; border-color: #8e44ad; }
#opops.theme--gray, #opopops.theme--gray { background-color: #95a5a6; }
#opops.theme--red, #opopops.theme--red { background-color: #e74c3c; }
#opops.theme--green, #opopops.theme--green { background-color: #2ecc71; }
#opops.theme--blue, #opopops.theme--blue { background-color: #3498db; }
#opops, #opopops {
width: 200px;
height: 50px;
background: red;
position: absolute;
top: 0;
}
#opops {
left: 0;
}
#opopops {
right: 0;
}
как сделать чтобы работал с
ByID и
ByClassName