I read Google . It seems to do correctly, but does not work. There are no errors in the console.
When the checked line is created, the link with the path to the css file, when there is no checked line is deleted. Recorded in localStorage (отображается в хранилище данные) .
I wrote an If condition, but when updating the page, the checked page is not set.
I do not know where to dig without errors in the console.
I work for the first time with localstorage
function darkTheme() { var checkbox = document.getElementById('darkTheme'), newLink = document.createElement('link'), head = document.getElementById('head'); if (checkbox.checked) { newLink.rel = "stylesheet"; newLink.href = "theme-for-night.css"; newLink.id = "link"; head.insertBefore(newLink, head.children[7]); //создать link на 7ой строчке родителя head localStorage.setItem('darkTheme', 'on'); //on если checked } else { link.remove(newLink); localStorage.setItem('darkTheme', 'off'); //off если убран checked } } window.onload = function() { if (localStorage.getItem('darkTheme') == 'on') { document.getElementById('darkTheme').checked = true; } } <head id="head"> <link href="styles.css" rel="stylesheet"> <!--Основной файл стилей--> <!--Эта строка добавляется если checked и удаляется если не checked. Файл с ночной темой--> <link href="theme-for-night.css" rel="stylesheet" id="link"> </head> Suddenly, it will help someone from the newbies:
<script> function darkTheme() { var inp = document.getElementById('darkTheme'); // if(inp.checked){ changeTheme();//Фунция добавить тему localStorage.setItem('darkTheme', 'on'); }else{ removeTheme();//Функция удалить тему localStorage.setItem('darkTheme', 'off'); } } //Включить тему, если darkTheme = 'on' function changeTheme() { var head = document.getElementById('head'), createLink = document.createElement('link'); // createLink.rel = "stylesheet"; createLink.href = "theme-for-night.css"; createLink.id = "link"; head.insertBefore(createLink, head.children[7]); } //Удалить тему, если darkTheme = 'off' function removeTheme() { var rm = document.getElementById('link'); rm.remove(); } //Функция на загрузку страницы window.onload = function() { var inp = document.getElementById('darkTheme'); if(localStorage.getItem('darkTheme') == 'on'){ changeTheme(); inp.checked = true; } } </script> <div> <!-- кнопка которая добавляет строчку с id="link" --> <input type="checkbox" id="darkTheme" onclick="darkTheme()"> </div>
var checkbox = document.getElementById('darkTheme')The first thing that caught my eye was that I did not find the name of thecheckboxvariable in the reserved words JS , but precisely because of this, your script does not seeinputand the second is not the name of thedar*l*Themefunctiondar*l*Themebut it should bedar*k*Theme- Air