0

How do you save data inside (li) elements to a text file from an Electron app? My code is not working. The li elements work dynamically so one is created when another task is entered. The saveFile() function is near the bottom of the script. The save button brings up the saveAs screen like it should. The problem is, the items in the li elements do not save to a text file like they should. How do I fix this issue?

<!DOCTYPE html>
<html>
<head>
<title>Task List</title>
<link rel="stylesheet" 


href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/
css/materialize.min.css">
</head>
<body>
<p id="saved"></p> 
<nav>
<div class="nav-wrapper">
  <a class="brand-logo center">Task List</a>  
</div>
</nav>
<ul id="taskList"></ul>
<button id='save'>Save File</button>
<button id='open'>Open File</button>


<script>
const electron = require('electron');
const {
    ipcRenderer
} = electron;
const ul = document.querySelector('ul');
const fs = require('fs');
const {
    dialog
} = require('electron').remote;


ipcRenderer.on('item:add', function(e, item) {
    ul.className = 'tasks';
    const li = document.createElement('li');
    li.className = 'task-item';
    const itemText = document.createTextNode(item);
    li.appendChild(itemText);
    ul.appendChild(li);
});
ipcRenderer.on('item:clear', function() {
    ul.className = '';
    ul.innerHTML = '';
});
ul.addEventListener('dblclick', removeItem);

function removeItem(e) {
    event.target.remove();
    if (ul.children.length == 0) {
        ul.className = '';
    }
}

function saveFile() {

    dialog.showSaveDialog((filename) => {
        if (filename === undefined) {
            alert('No files selected');
            return;
        }

        var tasks = document.getElementsByTagName('li').value

        fs.writeFile(filename[0], tasks, (err) => {
            if (err) {
                alert("Cannot update file", err.message);
                return;
            }
            document.getElementById('saved').textContent = 'Save Successful';
            alert('items saved', tasks);

        });
    })
};

or my code is in my gitHub account in the index.html file https://github.com/UgotGoosed/TaskList

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • When asking for help, it's best to format and indent the code in a readable, consistent way. (It's best when *not* asking for help, too.) I've run the script code through http://jsbeautifier.org/ for you (no affiliation). – T.J. Crowder Dec 12 '17 at 11:51
  • This is the problem (or at least two significant problems): `var tasks = document.getElementsByTagName('li').value` 1. The list returned by `getElementsByTagName` doesn't have a `value` property and is a **list** of matching elements. (See the linked dupetarget for details.) 2. `li` elements don't have a `value` property either. They have `innerHTML`, `innerText`, `textContent`, and similar. – T.J. Crowder Dec 12 '17 at 11:53

0 Answers0