Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
Saving values to localStorage() and making them stay when I reload the page in Javascript

I am currently making a note writing app and need your help.

I'm struggling to understand how localStorage() works and how exactly I saved things to it. I would like to reload the page and have every note that I've written not dissappear.

Thank you.

//// Declare Variables ////
const noteBtn = document.querySelector('.add-note-btn');
const writeNote = document.querySelector('.note-input');
const allSavedNotes = document.querySelector('.added-notes');

//// Write new note and add to list ////
noteBtn.addEventListener('click', function(e){
  // Create new paragraph element
  let newNote = document.createElement('p');
  // Add clas name to element
  newNote.className = 'saved-note';
  // Add the text input
  newNote.textContent = writeNote.value;
  // Append element to div
  allSavedNotes.appendChild(newNote);

  e.preventDefault();
})
<div class="all">
    <div>
      <div class="title">
        <h1 class="heading">Notes List</h1>
      </div>

      <div>
        <div class="writing-notes">
          <textarea class="note-input" cols="35" rows="10"></textarea>
          <a href="#" class="add-note-btn">Add note</a>
        </div>
        
        <div class="added-notes">
    
        </div>
      </div>
    </div>
  </div>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can save all notes in localStorage by appending the state to an empty array.

I've intitally created a state variable that contains earlier undefined or an empty array.

Then appendNotes function appends a paragraph to the allSavedNotes DOM selector.

//// Declare Variables ////
const noteBtn = document.querySelector('.add-note-btn');
const writeNote = document.querySelector('.note-input');
const allSavedNotes = document.querySelector('.added-notes');

const state = JSON.parse(localStorage.getItem('notes')) || [];

function appendNotes(text) {
  let p = document.createElement('p');
  p.textContent = text;
   
  // Append element to div
  allSavedNotes.appendChild(p);
}

// append notes on page load
state.map(s => appendNotes(s));

//// Write new note and add to list ////
noteBtn.addEventListener('click', function(e) {
  // Create new paragraph element
  let newNote = document.createElement('p');
  // Add class name to element
  newNote.className = 'saved-note';
  
  const text = writeNote.value.trim();

  // Add the text input
  newNote.textContent = text;
  
  // if there are no `notes` in `localStorage` then use empty array
  if (text !== "") {
      state.push(text)
    localStorage.setItem('notes', JSON.stringify(state));
   }
   
  // Append element to div
  appendNotes(text);
  
  newNote.textContent = "";
  
  e.preventDefault();
})
<div class="all">
  <div>
    <div class="title">
      <h1 class="heading">Notes List</h1>
    </div>

    <div>
      <div class="writing-notes">
        <textarea class="note-input" cols="35" rows="10"></textarea>
        <a href="#" class="add-note-btn">Add note</a>
      </div>

      <div class="added-notes">

      </div>
    </div>
  </div>
</div>

The above code won't from StackOverflow directly as it gives a cross-origin error:

Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.

But it works on JSFiddle. Here's a working link → https://jsfiddle.net/deadcoder0904/036bp9zy/33/

You can learn more about localStorage in this excellent blog post → https://www.digitalocean.com/community/tutorials/js-introduction-localstorage-sessionstorage

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda