The localStorage attribute is incapable of storing the href property of an element

When using the localStorage property like

localStorage.setItem('theme', element);
, keep in mind that it does not store the href property of an element such as
element.href = '../assets/css/syntax-highlighting/synthwave-84.css';
:

const lightButton = document.getElementById('theme-light');
const synthwaveButton = document.getElementById('theme-synthwave-84');
const body = document.body;
var check = document.getElementById('theme_css').classList[0] === 'theme-light';

const theme = localStorage.getItem('theme');
var element = document.getElementById('theme_css');

if (theme) 
{
  body.classList.add(theme);
}

synthwaveButton.onclick = () => 
{
  element.href = '../assets/css/syntax-highlighting/synthwave-84.css';
  localStorage.setItem('theme', element);

  body.classList.replace('theme-dark', 'theme-synthwave-84');
  body.classList.replace('theme-light', 'theme-synthwave-84');
  body.classList.replace('theme-cyberpunk', 'theme-synthwave-84');
  body.classList.replace('theme-tron', 'theme-synthwave-84');
  localStorage.setItem('theme', 'theme-synthwave-84');
};

Here is an example of the HTML:

<link rel="stylesheet" href="../assets/css/syntax-highlighting/suru-plus.css" id="theme_css" />

Answer №1

Storing DOM elements directly into LocalStorage is not possible as it only accepts strings, making JSON the preferred format for complex data. However, in the case of saving theme names – which are strings – this limitation does not pose an issue.

An alternative approach would be to create a unified function, changeTheme(), designed to handle all themes uniformly by utilizing an object to store available themes along with their respective CSS paths.

const themes = {
  "theme-dark": "../assets/css/syntax-highlighting/dark.css",
  "theme-light": "../assets/css/syntax-highlighting/light.css",
  "theme-cyberpunk": "../assets/css/syntax-highlighting/cyberpunk.css",
  "theme-tron": "../assets/css/syntax-highlighting/tron.css",
  "theme-synthwave-84": "../assets/css/syntax-highlighting/synthwave-84.css"
};

function changeTheme(newTheme) {
  var allThemes = Object.keys(themes);
  if (!allThemes.includes(newTheme)) return;
  allThemes.forEach(theme => document.body.classList.remove(theme));
  document.body.classList.add(newTheme);
  document.getElementById('theme_css').href = themes[newTheme];
  localStorage.setItem('theme', newTheme);
}

// connect buttons
document.querySelectorAll('.theme-switch').forEach(button => {
  button.onclick = () => changeTheme(button.id);
});

// load previous theme
changeTheme(localStorage.getItem('theme'));

By incorporating buttons like these, you can effortlessly implement a functional theme switcher without redundant code.

<button class="theme-switch" id="theme-synthwave-84">Synthwave 84</button>
<button class="theme-switch" id="theme-tron">Tron</button>

Alternatively, links or other mechanisms can also trigger changeTheme() based on your preference.

Answer №2

If you want to store values in local storage, they must be strings. Objects need to be serialized using JSON.stringify. Keep in mind that DOM elements cannot be serialized in the same way, as their properties are stored in the prototype of the element. To work around this limitation, you can directly set a specific property like this:

localStorage.setItem('theme-css', element.href);

Answer №3

Storing a DOM Element directly in LocalStorage is not possible. However, you can save the link as a LocalStorage entry instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transform a formatted currency amount into a double value by utilizing regex

I need to convert various currency formats into a double value. For example: 1,000,000.00 => 1000000.00 2'345',00 => 2345.00 2'344'334.03 => 1000000.03 The current solution I have is functional but inefficient. I am explorin ...

The readyState is stubbornly refusing to reach 4

I have been working on developing a dynamic AJAX search bar that interacts with my database. Below is the code I have been using. function getXmlHttpRequestObject(){ if(window.XMLHttpRequest){ return new XMLHttpRequest(); } else if (window.ActiveXObj ...

What are the steps to resolving an Unhandled promise rejection error in a Node.js application?

I encountered an error message that I need help resolving: I am faced with an unhandled promise rejection. This issue likely occurred due to throwing inside an async function without a catch block, or rejecting a promise without handling it using .catch( ...

Help with CSS and React - how to position text in front of an image

Currently, I am working on positioning text on top of an image and centering it within the parent div. You can see the desired design in the screenshot below: https://i.sstatic.net/NNidz.png After experimenting with code and using z-index to layer the te ...

What is the best way to modify the height of an element that contains an SVG at the bottom in order to ensure it appears visually appealing across all screen widths?

Is there a way to adjust the height of an element with an SVG at the bottom so that it looks good on all screen widths? I'm attempting to create a 'wave' effect at the bottom of my element using a background-image in CSS. Although I managed ...

What are the steps to troubleshoot and resolve validation errors while using the paypal-rest-sdk?

I'm currently experimenting with the paypal-rest-sdk to learn how to integrate PayPal checkout into my website. However, I've encountered an issue during testing where whenever I click submit in my form, I receive a "localhost refused to connect" ...

"Defining a CSS class specifically for styling the span element nested within an

The HTML structure I am working with is as follows: <p> <a href="#"> <span class = "class-for-span"> SOME TEXT HERE </span> </a> </p> Along with the following CSS: p a{ color: grey; text-decora ...

Working with JavaScript Arrays within a JSON file data

I am currently learning React and attempting to display random images from the Picsum website using their API. The JSON file I receive contains various information, but I am specifically interested in extracting the image URLs. Although it appears that my ...

Retrieval of stored information using Vue CLI, Vuex, and PWA

Is it possible to access cached data from a service worker in the vuex store while offline? My app functions properly in offline mode in the browser, but when added to the home screen with the manifest.json file, it fails to display the cached data and on ...

Is there anyone who can assist me with the problem I'm facing where Javascript post call is sending a null value to my mongoDB

As a beginner in JS, NodeJS, and MongoDB, I decided to create a quiz website to sharpen my coding skills. However, I have encountered an issue while trying to send the username (string) and total marks (int) to MongoDB using the Post method. Surprisingly, ...

Ajax loaded scripts are unable to access global variables

Index.html <script> let bar = 1; </script> This html page is being loaded multiple times on the page using AJAX: article.html <script> if (bar === 1) { // perform a task } // Error: bar is not defined </script> Bar is a simple ...

Modify the hyperlink address in the body of the webpage using jQuery

I'm searching for a solution to modify the href attribute in the following code: <link rel="stylesheet" type="text/css" href="theme1.css"> For instance, changing it from: <link rel="stylesheet" type="text/css" href="theme1.css"> to: & ...

Tips for including multiple array values in an AJAX URL

I have a challenge passing multiple values in the URL to my controller class all at once. However, only the last value is being passed in the URL. function submitFormData(formData) { var x = []; for(var i = 0;i < formData.length ;i++ ){ alert(i); ...

What is the proper method for incorporating text into d3.js nodes?

As I venture into the world of d3.js, I've decided to experiment with some sample code from this particular page and tweak it according to my needs. My main goal is to include TEXT within the colored nodes. Although these nodes already have a title p ...

Leveraging AngularJS html5mode in conjunction with express.js

Client-side: when("/page/:id", { templateUrl: "partials/note-tpl.html", controller : "AppPageController" }); $locationProvider.html5Mode( true ); Html: <a ng-href="/page/{{Page._id}}">{{Page.name}}</a> Server-side: app.use("/pag ...

Get rid of the rollover effect on the <a> tag when hovering over an image

I have a snippet of code that is fully functional. <div class="user-pic round-pic"> <a href="<?php echo $userLoggedIn; ?>"><img src="<?php echo $user['profile_pic']; ?>"></a> </div> The issue lies in i ...

The execution of my JavaScript code does not pause for the completion of an ajax request

I'm currently working on a register validation code in JavaScript. One of the key aspects checked by the validation function is whether the email address provided by the user already exists in the database. To handle this, I'm implementing ajax, ...

Steps for modifying the look of a button to display an arrow upon being clicked with CSS

Looking to enhance the visual appearance of a button by having an arrow emerge from it upon clicking, all done through CSS. Currently developing a React application utilizing TypeScript. Upon clicking the next button, the arrow should transition from the ...

Ways to extract a number that comes after a specific word in a URL

I have a URL and need to extract a specific value from it by removing a certain step. I am looking for a regex solution to accomplish this task For example, if I have the window.location.href, the URL might look like this: https://mypage/route/step-1/mor ...

Using Three.js to Manipulate Objects through Their Names

Is there a way to access multiple meshes with the same name? var mesh1 = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { color: 0xffffff })); mesh1.name = "meshes"; scene.add( mesh1); var mesh2 = new THREE.Mesh( geometry, new THREE.MeshBasicMate ...