Delete a card from the DOM and at the same time delete from the localStorage the data contained in this

1

Recently I started my first project with JavaScript (my first language). It is a note application, where when creating a new one an element is created that is added to the DOM and at the same time to the localStorage and the opposite should happen when the note is deleted, but my problem is in the part where I try to erase the data of the note that are in localStorage .

How can I do that function? I have tried to give solution in several ways. One of those solutions results in erasing everything except the one I want to erase, and I could not do anything to make it happen otherwise.

In another I delete the note I want but it returns a lot of notes that contain each of the characters of the note to be deleted, and the others of plane do not help me.

Note: The last function is the one I can not do.

Code:

const lista = document.getElementById('list');

function eventlisteners() {
    document.getElementById('btn-saved').addEventListener('click', agregarNotaDom);

    lista.addEventListener('click', borrarNotaDom);

    document.addEventListener('DOMContentLoaded', cargarData)
}
eventlisteners();

function agregarNotaDom() {
    let titulo = document.getElementById('title').value;
    let cuerpo = document.getElementById('body').value;
    // Contenedor de la nota
    let nota = document.createElement('div');
    nota.className = 'card bg-light mb-3';
    // Contenedor del header
    let header = document.createElement('div');
    header.className = 'card-header header-nota';
    // Titulo de la nota
    let tituloNota = document.createElement('p');
    tituloNota.textContent = titulo;
    // Boton borrar
    let btnDelete = document.createElement('button');
    btnDelete.className = 'borrar-nota';
    btnDelete.textContent = 'Borrar';
    // contenedor del body
    let bodyNota = document.createElement('div');
    bodyNota.className = 'card-body';
    // contenido nota
    let contenidoNota = document.createElement('p');
    contenidoNota.className = 'card-text';
    contenidoNota.textContent = cuerpo;
    
    lista.appendChild(nota);
    // HEADER
    nota.appendChild(header);
    header.appendChild(tituloNota);
    header.appendChild(btnDelete);
    // BODY
    nota.appendChild(bodyNota);
    bodyNota.appendChild(contenidoNota);

    guardarLocalStorage(titulo, cuerpo);
}
function borrarNotaDom(e, titulo, cuerpo){
    e.preventDefault();
    if(e.target.className === 'borrar-nota'){
        e.target.parentElement.parentElement.remove();
        console.log(e.target.parentElement.parentElement.remove())
    }
}
function guardarLocalStorage(titulo, cuerpo) {
    let titulos;
    let cuerpos;

    titulos = obtenerNotasTitulosLocalStorage();
    cuerpos = obtenerNotasCuerposLocalStorage();

    titulos.push(titulo);
    cuerpos.push(cuerpo);

    localStorage.setItem('titulos', JSON.stringify(titulos));
    localStorage.setItem('cuerpos', JSON.stringify(cuerpos));
}
function obtenerNotasTitulosLocalStorage(){
    let titulos;
   
    if (localStorage.getItem('titulos') === null) {
        titulos = [];

    } else {
        titulos = JSON.parse(localStorage.getItem('titulos') ); 
    }
    return titulos;
}
function obtenerNotasCuerposLocalStorage(){
     let cuerpos;
     if (localStorage.getItem('titulos') === null) {

        cuerpos = [];
    } else {
        cuerpos = JSON.parse(localStorage.getItem('cuerpos') ); 
    }
    return cuerpos;
}
function cargarData(){
    let titulos = obtenerNotasTitulosLocalStorage();
    let cuerpos = obtenerNotasCuerposLocalStorage();

    for(let i = 0; i < titulos.length; i++){

        // Contenedor de la nota
        let nota = document.createElement('div');
        nota.className = 'card bg-light mb-3';
        // Contenedor del header
        let header = document.createElement('div');
        header.className = 'card-header header-nota';
        // Titulo de la nota
        let tituloNota = document.createElement('p');
        tituloNota.textContent = titulos[i];
        // Boton borrar
        let btnDelete = document.createElement('button');
        btnDelete.className = 'borrar-nota';
        btnDelete.textContent = 'Borrar';
        // contenedor del body
        let bodyNota = document.createElement('div');
        bodyNota.className = 'card-body';
        // contenido nota
        let contenidoNota = document.createElement('p');
        contenidoNota.className = 'card-text';
        contenidoNota.textContent = cuerpos[i];
        
        lista.appendChild(nota);
        // HEADER
        nota.appendChild(header);
        header.appendChild(tituloNota);
        header.appendChild(btnDelete);
        // BODY
        nota.appendChild(bodyNota);
        bodyNota.appendChild(contenidoNota);
    }
}
function borrarNotaLocalStorage(){
    
}
body{
    font-family: 'Raleway', sans-serif;
    margin-bottom: 50px;
}
.container{
    width: 100%;
    background-color: red;
}
.list{
    width: 90%;
    margin: 20% auto;
}
.bottomNav{
    background-color: #385b80;
    padding: 5px 10px;
    width: 90%;
    border-radius: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    bottom: 5px;
    left: 5%;
    position: fixed;
}
.btn-main{
    border-radius: 25px;
    width: 22%;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.btn-main > img{
    width: 65%;
}
/* MENU DESPLEGABLE */

.sub-menu{
    width: 90%;
    height: 400%;
    padding: 5px 0;
    position: absolute;
    bottom: 118%;
    left: 5%;
    border:2px solid #ccc;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    display: none;
    background-color: #d5d4d4;
    color: #3399F3;
}
.note{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
    width: 100%;
    margin: 10px;
}
.title{
    margin-bottom: 0;
}
.note > .size-back{
    width: 80%;
    padding: 5px 5px;
    margin-bottom: 5px;
    border-radius: 5px;
    border:2px solid #ccc;
    color: rgb(116, 113, 113);
    text-align: center;
    font-size: 14px;
}
.note > textarea{
    height: 100px;;
}
.btn-saved{
    border: 1px solid gray;
    font-size: 14px;
    padding: 5px 15px;
}
.btn-saved:hover{
    color: white;
    background-color: #3399F3;
}
/* TRIANGLE */
span{
    color : #ccc;
    position: absolute;
    font-size: 36px;
    bottom: -18%;
    /* display: none; */
}

.btn-main:hover  > .sub-menu{
    display: flex;
}
/* elementos */

.header-nota{
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.header-nota > p{
    margin-bottom: 0;
}
.borrar-nota{
    background-color: rgb(253, 47, 47);
    color: #fff;
    font-weight: 400;
    padding: 0.375rem 0.75rem;
    border: 0;
    border-radius: 0.25em;
}
.borrar-nota:focus{
    outline: none;
}
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>app</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    
    <link rel="stylesheet" href="css/fontello.css">
    <link rel="stylesheet" href="css/estilosPanel.css">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>

    <style type="text/css">div.image {max-width: 256px;max-height: 256px;
    background-image: url(data:image/svg+xml;utf8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTkuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4PSIwcHgiIHk9IjBweCIgdmlld0JveD0iMCAwIDUyIDUyIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCA1MiA1MjsiIHhtbDpzcGFjZT0icHJlc2VydmUiIHdpZHRoPSIzMnB4IiBoZWlnaHQ9IjMycHgiPgo8Zz4KCTxwYXRoIGQ9Ik0yNiwwQzExLjY2NCwwLDAsMTEuNjYzLDAsMjZzMTEuNjY0LDI2LDI2LDI2czI2LTExLjY2MywyNi0yNlM0MC4zMzYsMCwyNiwweiBNMjYsNTBDMTIuNzY3LDUwLDIsMzkuMjMzLDIsMjYgICBTMTIuNzY3LDIsMjYsMnMyNCwxMC43NjcsMjQsMjRTMzkuMjMzLDUwLDI2LDUweiIgZmlsbD0iIzAwMDAwMCIvPgoJPHBhdGggZD0iTTM4LjUsMjVIMjdWMTRjMC0wLjU1My0wLjQ0OC0xLTEtMXMtMSwwLjQ0Ny0xLDF2MTFIMTMuNWMtMC41NTIsMC0xLDAuNDQ3LTEsMXMwLjQ0OCwxLDEsMUgyNXYxMmMwLDAuNTUzLDAuNDQ4LDEsMSwxICAgczEtMC40NDcsMS0xVjI3aDExLjVjMC41NTIsMCwxLTAuNDQ3LDEtMVMzOS4wNTIsMjUsMzguNSwyNXoiIGZpbGw9IiMwMDAwMDAiLz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8L3N2Zz4K)}
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light navigator-title">
        <h1 class="navbar-brand  medio title">Lista de Tareas</h1>
        <button type="button" class="btn btn-secondary disabled bnt-back" onclick="location.href='index.html'">Cerrar</button>

    </nav>
    <div class="list" id="list">
        <!-- <div class="card bg-light mb-3" style="max-width: 20rem;">
                <div class="card-header">Header</div>
                <div class="card-body">
                  <h4 class="card-title">Light card title</h4>
                  <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                </div>
              </div> -->
      </div>
    <nav class="bottomNav">
        <button class="btn btn-primary btn-main" id="btnCreate" >
            <div class="sub-menu">
                <div class="titulo" class="size-back title"><p>Nueva nota</p></div>
                <div class="note">
                    <input type="text" id="title" class="size-back" placeholder="Dale un nombre a tu nota">
                    <textarea cols="30" rows="10" id="body" class="size-back" placeholder="Escribe tu nota aqui"></textarea>
                </div> 
                <div id="btn-saved" class="btn-saved">Crear nota</div>
                <span class="icon icon-down-dir"></span>
            </div> 
            <img src="data:image/svg+xml;utf8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTkuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjxzdmcgeG1sbnM9Imh0dHA6Ly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/main.js"></script>
</body>
</html>
    
asked by jesus m velasco 23.12.2018 в 07:26
source

1 answer

1

In the first place and how you treat as atomic operations the actions of adding and deleting notes I would make a function for each of them, where internally you call the functions that each of the operations involved do, that is, we start from :

function addNote() {
    addToDOM();
    addToLocalStorage();
}

function delNote() {
    delFromDOM();
    delFromLocalStorage();
}

with the corresponding arguments in each case.

Another thing, you can save a lot of code by creating some generic functions, for example:

function $(id) {
    return document.getElementById(id);
}

and to use it:

let title = $('title').value;


Regarding your problem: How to delete a data from the LocalStrorage?

Yes to store a data:

localStorage.setItem("name", "MiNombre");

to eliminate that same data:

localStorage.removeItem("name");


To learn more about how storage in the browser works, you can visit the MDN page .


  

Edited

To delete a specific note, starting from your function:

function guardarLocalStorage(titulo, cuerpo) {
    let titulos;
    let cuerpos;

    titulos = obtenerNotasTitulosLocalStorage();
    cuerpos = obtenerNotasCuerposLocalStorage();

    titulos.push(titulo);
    cuerpos.push(cuerpo);

    localStorage.setItem('titulos', JSON.stringify(titulos));
    localStorage.setItem('cuerpos', JSON.stringify(cuerpos));
}

You can write a function that removes the note by rewriting the storage after removing the note . The usual thing would be to work with an ID for each note, in your case I will assume that the title of the note is unique, if not you would use title and description to locate the position of the note you are going to erase.

function clearNoteFromLocalStorage(title) {
    let titulos;
    let cuerpos;

    titulos = obtenerNotasTitulosLocalStorage();
    cuerpos = obtenerNotasCuerposLocalStorage();

    /**
     * Localizamos la posición de la nota a borrar
     *
     */
    let pos = titulos.indexOf(title);

    /**
     * Borramos la nota de los arrays (de titulos y de cuerpos)
     *
     */
    titulos.splice(pos, 1);
    cuerpos.splice(pos, 1);

    /**
     * Reescribimos el almacenamiento sin la nota en cuestion
     *
     */
    localStorage.setItem('titulos', JSON.stringify(titulos));
    localStorage.setItem('cuerpos', JSON.stringify(cuerpos));
}


Once everything is working you can optimize code, for example:

function obtenerNotasCuerposLocalStorage(){
    let cuerpos;
    if (localStorage.getItem('titulos') === null) {
        cuerpos = [];
    } else {
        cuerpos = JSON.parse(localStorage.getItem('cuerpos')); 
    }
    return cuerpos;
}

can be rewritten as:

function obtenerNotasCuerposLocalStorage(){
    let cuerpos = [];
    if (localStorage.getItem('titulos') !== null) {
       cuerpos = JSON.parse(localStorage.getItem('cuerpos')); 
    }
    return cuerpos;
}
    
answered by 23.12.2018 в 11:07