How to delete DOM element and related array index at same time? - javascript

Edit: Never mind...I give up...I'm done with studying web dev...
I have an array (myLibrary) of "book" objects that are pushed into said array when a user submits input from a form.
let myLibrary = [];
function Book(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}
function addToLibrary() {
let Newbook = new Book(
titleInput.value,
authorInput.value,
pagesInput.value,
readInput.checked
);
myLibrary.push(Newbook);
}
Upon submitting, a card is also generated on the DOM displaying the information from the form. I also add a delete button on each dynamically generated card. I am able to delete the card itself using an event listener (in bold), but I am unable to also delete the related object in the array.
function renderBookCard() {
const newCard = document.createElement("div");
const removeBook = document.createElement("img");
const bookTitleDiv = document.createElement("div");
const titleLabel = document.createElement("p");
const dynamicTitle = document.createElement("p");
const authorDiv = document.createElement("div");
const authorLabel = document.createElement("p");
const dynamicAuthor = document.createElement("p");
const pagesDiv = document.createElement("div");
const pagesLabel = document.createElement("p");
const dynamicPages = document.createElement("p");
const readDiv = document.createElement("div");
const dynamicRead = document.createElement("p");
//
MainBookContainer.appendChild(newCard);
newCard.appendChild(removeBook);
removeBook.classList.add("trash");
removeBook.setAttribute(
"src",
"./Images/delete_FILL0_wght400_GRAD0_opsz48.svg"
);
newCard.classList.add("book-card-container");
newCard.appendChild(bookTitleDiv);
bookTitleDiv.classList.add("book-title");
newCard.appendChild(titleLabel);
titleLabel.textContent = `Title:`;
newCard.appendChild(dynamicTitle);
newCard.appendChild(authorDiv);
authorDiv.classList.add("book-author");
newCard.appendChild(authorLabel);
authorLabel.textContent = `Author:`;
newCard.appendChild(dynamicAuthor);
newCard.appendChild(pagesDiv);
pagesDiv.classList.add("book-pages");
newCard.appendChild(pagesLabel);
pagesLabel.textContent = `Pages:`;
newCard.appendChild(dynamicPages);
newCard.appendChild(readDiv);
readDiv.classList.add("book-read");
newCard.appendChild(dynamicRead);
//
let i;
for (i = 0; i < myLibrary.length; i++) {
dynamicTitle.textContent = myLibrary[i].title;
dynamicAuthor.textContent = myLibrary[i].author;
dynamicPages.textContent = myLibrary[i].pages;
if (!readInput.checked) {
dynamicRead.textContent = "Unread";
} else {
dynamicRead.textContent = "Read";
}
}
//
**newCard.addEventListener("click", function (e) {
if (e.target.classList.contains("trash")) {
newCard.remove();
myLibrary.splice([i], 1);**
}
});
}
How am I able to delete the card and the related object in the array? I hope I was able to ask in a clear way. If not I apologize.

Here is my example. I think it might help you.
*If you have many elements to append to your HTML feel free to use insertAdjacentHTML or other methods, this will help you easily to organize your code.
*In my case, I use the filter method to update my list.
let bookList = [];
const addBook = document.querySelector("#add_book");
const bookWrap = document.querySelector("#book_wrap");
addBook.addEventListener("click", () => {
const bookName = document.querySelector("#book_name");
const bookAuthor = document.querySelector("#book_author");
bookList.push({
book_name: bookName.value,
book_author: bookAuthor.value
})
const bookTemplate = `
<div class="book">
<div>
<h2>${bookName.value}</h2>
<p>${bookAuthor.value}</p>
</div>
<div>
<button id="trash_${bookName.value}">Trash</button>
</div>
</div>`;
bookWrap.insertAdjacentHTML("beforeend", bookTemplate);
// console.log(bookList)
document.querySelector(`#trash_${bookName.value}`)
.addEventListener("click", (e) => {
e.target.closest(".book").remove();
bookList = [...bookList.filter(item => item.book_name !== e.target.id.split("_")[1])]
// console.log(bookList)
})
bookName.value = null;
bookAuthor.value = null;
})
.book-wrap {
min-width: 250px;
min-height: 200px;
border-radius: 10px;
border: 1px solid black;
margin: 20px 0;
padding: 20px;
}
.book {
display: flex;
justify-content: space-between;
width: 200px;
gap: 40px;
margin-bottom: 20px;
}
h2,
p{
margin: 0;
}
p {
color: #999;
}
<div>
<div style="margin-bottom: 10px;">
<label for="book_name">Book name:</label><br/>
<input id="book_name" type="text" />
</div>
<div style="margin-bottom: 10px;">
<label for="book_author">Author name:</label><br/>
<input id="book_author" type="text" />
</div>
<div>
<button id="add_book">Add Book</button>
</div>
<div id="book_wrap" class="book-wrap"></div>
</div>
Hope this might help you.
Enjoy the journey into Web dev.

Related

Retrieve array of objects from local storage

Trying to make to-do list but I have difficulties with local storage. First i don't understand why does local storage returns [object Object] instead of actual text. Secondly at some point local storage becomes empty and then begins to fill in from the beginning. That's so confusing for me
function addTask() {
let addTaskButton = document.getElementById('add-task-button')
let list = document.getElementById('task-list');
let li = document.createElement('li');
let checkbox = document.createElement('input');
let taskText = document.createElement('span');
let delButton = document.createElement('button');
let btnText = document.createTextNode('Delete task');
checkbox.type = 'checkbox';
checkbox.className = 'checkbox';
taskText.innerText = document.getElementById('input-task').value;
taskText.className = 'task';
delButton.className = 'delete-btn';
delButton.addEventListener('click', deleteTask)
delButton.addEventListener('click', updateStorage)
addTaskButton.addEventListener('click', updateStorage);
delButton.appendChild(btnText);
li.appendChild(checkbox);
li.appendChild(taskText);
li.appendChild(delButton);
list.appendChild(li);
document.getElementById('input-task').value = '';
taskList.push({
text: taskText.innerText,
checked: false
});
}
let taskList = [];
function updateStorage() {
localStorage.setItem('tasks', JSON.stringify(taskList));
console.log(taskList)
}
function deleteTask () {
this.parentNode.remove();
}
document.getElementById('add-task-button').addEventListener('click', addTask);
function loadList() {
document.querySelector('ul').innerHTML = JSON.parse(localStorage.getItem('tasks')) || [];
}
window.addEventListener('load', loadList);
this way:
const
inputTask = document.querySelector('#input-task')
, addTaskBt = document.querySelector('#add-task-button')
, taskList = document.querySelector('#task-list')
, tasks = JSON.parse(localStorage.getItem('tasks') || '[]')
, savTasks =_=> localStorage.setItem('tasks',JSON.stringify(tasks))
;
tasks.forEach( newLItask )
addTaskBt.onclick =_=>
{
if (inputTask.value.trim()==='') return
let taskElm = { txt: inputTask.value.trim(), checking:false }
tasks.push( taskElm )
newLItask( taskElm )
savTasks()
inputTask.value = ''
inputTask.focus()
}
taskList.onclick = ({target}) => // event delegayion for all buttons & checkboxes
{
if (!target.matches('button.delete-btn, input[type=checkbox]')) return
let taskIndex = tasks.findIndex(task => task===target.closest('li').ref )
if (target.matches('input[type=checkbox]'))
tasks[taskIndex].checking = target.checked
else // delete
{
tasks.splice(taskIndex,1)
target.closest('li').remove()
}
savTasks()
}
function newLItask( taskElm )
{
taskList
.appendChild(Object.assign(document.createElement('li'), {ref:taskElm} ))
.innerHTML = `
<input type="checkbox" class="checkbox" ${taskElm.checking ? 'checked': ''}>
<span class="task"> ${taskElm.txt} </span>
<button class="delete-btn">Delete task</button>`
}
for testing:
#task-list {
padding : 0;
list-style-type : none;
}
#task-list li {
margin : .4em 0;
}
#task-list li > span {
display : inline-block;
width : 20em;
border-bottom : 1px solid lightsteelblue;
margin : 0 .6em 0 0;
}
#task-list input[type=checkbox]:checked + span {
text-decoration : line-through ;
text-decoration-style : wavy;
text-decoration-color : orangered;
}
<input type="text" id="input-task" placeholder="input task" size="26">
<button id="add-task-button" >add task</button>
<ul id="task-list"></ul>
I made this a comment on the original post, but I think this might qualify as the answer...
The JSON.parse gets you an object, and when you try to use that object as a string (setting the innerHTML of an element), you'll get the "[object Object]" text. What's stored in localStorage is a string already that represents your JSON. Just set the innerHTML to what comes back from your localStorage.getItem('tasks') call.

Display slider when you hover over array elements and give value to the array elements

I have done the part where you have to generate the array elements when you enter them from textbox, what I struggle with now is to display a slider on hover over each array element and give the array element a value, also what I struggle with is to delete each generated array element individually, my delete function deletes the entire array on click not just the single element I click.
Here is how it should look like:
enter image description here
Here is my code so far:
let names = [];
let nameInput = document.getElementById("name");
let messageBox = document.getElementById("display");
function insert ( ) {
names.push( nameInput.value );
clearAndShow();
}
function remove()
{
var element = document.getElementById("display");
element.parentNode.removeChild(element);
}
function clearAndShow () {
let printd=""
nameInput.value = "";
messageBox.innerHTML = "";
names.forEach(function(element){
if(element != ''){
var _span = document.createElement('span');
_span.style.borderStyle = "solid"
_span.style.borderColor = "blue"
_span.style.width = '50px'
_span.style.marginLeft = "5px"
_span.appendChild(document.createTextNode(element))
messageBox.appendChild(_span)
printd +="''" + element + "''" + "," + " ";
document.getElementById("labelprint").innerHTML=(printd)
}
})
}
h3 {
color: rgb(0, 174, 255);
}
.container {
border: solid 2px;
display: block;
margin-left: 200px;
margin-right: 200px;
margin-top: 50px;
}
<div class="container">
<form>
<h1>Enter Search</h1>
<input id="name" type="text" />
<input type="button" value="Search" onclick="insert()" />
</form>
<br/>
<div onclick="remove(this)" id="display"></div>
<br/>
<label >You have Selected: </label>
<h3 id="labelprint"></h3>
</div>
I am not being rude I just got confused on how you stated your message but what I think you are saying is to do this:
var names = [];
var nameInput = document.getElementById("name");
var messageBox = document.getElementById("display");
function insert ( ) {
names.push( nameInput.value );
// add value to array val: names[names.length - 1] = PutValueHere
clearAndShow();
}
function remove(this){
document.getElementById("display").parentNode.firstChild.remove(); // If you want it to remove the last child with the id 'display' then do .parentNode.lastChild.remove()
//if you are trying to remove the last val in the array do this: names.splice(names.length-1,1) for the first do this names.splice(0,1)
}
function clearAndShow () {
var printd=""
nameInput.value = "";
messageBox.innerHTML = "";
names.forEach(function(element){
if(element != ''){
var _span = document.createElement('span');
_span.id = '_spanId'
$('_spanId').css('border-style',solid');
$('_spanId').css('border-color',blue');
$('_spanId').css('width',50+'px');
$('_spanId').css('margin-left',5+'px');
_span[0].appendChild(document.createTextNode(element))
messageBox[0].appendChild(_span)
printd += "''" + element + "'', ";
document.getElementById("labelprint").innerHTML = printd
}
})
}
I have tried to implement something that i hope it's close to what are you looking for:
HTML:
<div class="container">
<form>
<h1>Add new slider</h1>
<input id="sliderName" type="text" />
<input type="button" value="Add" onclick="insertSlider()" />
</form>
<div id="display"></div>
</div>
CSS:
h3 {
color: rgb(0, 174, 255);
}
.container {
border: solid 2px;
display: block;
margin-left: 200px;
margin-right: 200px;
margin-top: 50px;
}
JS:
let messageBox = document.getElementById("display");
function deleteFn(id) {
const element = document.getElementById(id)
if(element) element.outerHTML="";
}
function onChangeSlideId(id){
const elementSlide = document.getElementById('slider-'+id+'')
if(elementSlide){
const value = elementSlide.value
const elementSlideText = document.getElementById('slider-value-'+id+'')
elementSlideText.innerText = '('+value+')'
}
}
function insertSlider(){
const name = document.getElementById("sliderName")
const nameValue = name.value
const newLabel = document.createElement('label')
newLabel.setAttribute('for',nameValue)
newLabel.innerText = nameValue
const newSlider = document.createElement('input')
newSlider.setAttribute('id','slider-'+nameValue+'')
newSlider.setAttribute('type','range')
newSlider.setAttribute('name',nameValue)
newSlider.setAttribute('onchange','onChangeSlideId("'+nameValue+'")')
const sliderValue = document.createElement('span')
sliderValue.setAttribute('id','slider-value-'+nameValue+'')
sliderValue.innerText = '('+newSlider.value+')'
const newContainer = document.createElement('div')
newContainer.setAttribute('id',nameValue)
newContainer.setAttribute('style','display: grid')
newContainer.appendChild(newSlider)
newContainer.appendChild(newLabel)
newContainer.appendChild(sliderValue)
const newDeleteButton = document.createElement('input')
newDeleteButton.setAttribute('type', 'button')
newDeleteButton.setAttribute('value', 'Delete ' + nameValue + '')
newDeleteButton.setAttribute('onclick', 'deleteFn("'+nameValue+'")')
newContainer.appendChild(newDeleteButton)
messageBox.appendChild(newContainer)
}
You can try it by yourself in this codepen

Trying to get values from multiple inputs

I'm trying to make a very basic expense tracker by building off the foundation of a todo app with vanilla Javascript. I'm having trouble isolating the value of all three input bars and getting them to display on the page. At the moment I'm getting 3 [objectHTMLInputElement] and undefined. I'd just like to know if I'm on the right track or if there's an easier way to isolate multiple input values and get them to display on the page. If somebody could point me in the right direction that'd be awesome. Thanks!
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
let inputName = document.getElementById('input-name');
let inputDate = document.getElementById('input-date');
let inputAmount = document.getElementById('input-amount');
let inputAll = document.querySelectorAll('.input-all');
let expenses = [
]
function add() {
let inputs = inputAll.value;
if (inputs == '') {
return true;
}
expenses.push(inputs);
displayExpenses();
}
function remove() {
}
function displayExpenses() {
let expensesUl = document.getElementById('expenses-ul');
expensesUl.innerHTML = `${inputName}${inputDate}${inputAmount}`;
for (var i = 0; i < expenses.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = expenses[i];
expensesUl.appendChild(expensesLi);
}
}
* {
padding: 0;
box-sizing: border-box;
}
.headings {
text-align: center;
}
.headings h1 {
font-size: 3rem;
font-family: 'Courier New', Courier, monospace;
}
.headings h2 {
margin-top: -20px;
}
form {
text-align: center;
}
#input-name {
width: 50%;
}
#input-date {
width: 18%;
margin-right: 160px;
}
#input-amount {
width: 18%;
margin-left: 18px;
}
#add-btn {
margin-top: 50px;
margin-left: 800px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Expense Tracker</title>
</head>
<body>
<div class="headings">
<h1>Expense Tracker</h1>
<h2>Add A New Item</h2>
</div>
<form>
<label>Name:</label>
<input class="input-all" id="input-name">
<br>
<br>
<label>Date:</label>
<input class="input-all" id="input-date">
<label>Amount:</label>
<input class="input-all" id="input-amount">
</form>
<button id="add-btn">Add Expense</button>
<ul id="expenses-ul"></ul>
<script src="main.js"></script>
</body>
</html>
Try this
const btn = document.getElementById('btn');
btn.addEventListener('click', function (event) {
const form = document.getElementById('form');
const output = document.getElementById('output');
const data = Object.fromEntries(new FormData(form).entries());
output.innerHTML = JSON.stringify(data, undefined, 2);
});
.wrap{
display: flex;
}
#output{
margin-left:50px;
border-width:3px;
border-style:dashed;
border-color:#FFAC55;
padding:5px;
min-width: 150px;
min-height: 80px;
}
<div class="wrap">
<div>
<form id="form">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="date">Date:</label><br>
<input type="text" id="role" name="role"> <br>
<label for="lname">Amount:</label><br>
<input type="text" id="amount" name="amount"><br><br>
<input id="btn" type="button" value="Print all value">
</form>
</div>
<div>
<pre id="output">
</pre>
</div>
</div>
When using document.querySelectorAll it's return a [NodeList] that consists of all selected elements on the other side there's also document.getElementsByClassName that return [HTMLCollection] - whatever you used you need to loop through to get the value of every selected input
When you passed [HTMLInputElement] as innerHTML of expensesUl it's will return the element object name not the value of this element because you are not selected any property of this object so you can't set an object as innerHTML of html element
if you want the right way of this part it's will be like that
let inputName = document.getElementById('input-name');
let inputDate = document.getElementById('input-date');
let inputAmount = document.getElementById('input-amount');
let expensesUl = document.getElementById('expenses-ul');
//this will give you empty string because they aren't get a value yet
expensesUl.innerHTML = `name = ${inputName.value}, date = ${inputDate.value}, amoute = ${inputAmount.value}`;
but now because we are selected all elements we are not need to select every input one by one anymore we will make a loop so we will loop through inputAll var to get the value of [HTMLInputElement] object
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
function add() {
let inputAll = document.querySelectorAll('.input-all');
for(var i of inputAll) {
if (i.value == '') {
return "Sorry you need to fill all inputs"
}
}
displayExpenses(inputAll);
}
function displayExpenses(elements) {
let expensesUl = document.getElementById('expenses-ul');
for (var i = 0; i < elements.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = elements[i].value
expensesUl.appendChild(expensesLi);
}
}
at the example above i removed expenses array but if you want to use it to take the value of the inputs you can make it like that
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
function add() {
let inputAll = document.querySelectorAll('.input-all');
let expenses = []
for(var i of inputAll) {
if (i.value == '') {
return "Sorry you need to fill all inputs"
}
expenses.push(i.value)
}
displayExpenses(expenses);
}
function displayExpenses(values) {
let expensesUl = document.getElementById('expenses-ul');
for (var i = 0; i < values.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = values[i]
expensesUl.appendChild(expensesLi);
}
}
the whole code should to be like that
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
let inputName = document.getElementById('input-name');
let inputDate = document.getElementById('input-date');
let inputAmount = document.getElementById('input-amount');
let inputAll = document.querySelectorAll('.input-all');
let expenses = []
function add() {
for(var i of inputAll) {
if (i.value == '') {
return true
}
expenses.push(i.value)
}
displayExpenses();
}
function displayExpenses() {
let expensesUl = document.getElementById('expenses-ul');
expensesUl.innerHTML = `${inputName.value}, ${inputDate.value}, ${inputAmount.value}`;
for (var i = 0; i < expenses.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = expenses[i];
expensesUl.appendChild(expensesLi);
}
}
about document.getElementsByClassName, document.querySelectorAll one deferant is that you can use array methods like forEach() with document.querySelectorAll while you can't do that with document.getElementsByClassName

How to update created elements?

I have this simple function that will create a paragraph.
function appendElements() {
const input = document.getElementById("myInput");
const createDiv = document.createElement("div");
createDiv.classList.add("myDiv");
const createP = document.createElement("P");
createP.classList.add("myParagraph");
createP.innerHTML = input.value;
createDiv.appendChild(createP);
const div = document.getElementById("examplediv");
div.appendChild(createDiv);
}
And another function that will sum the innerHTML of the divs, and create a div element for the result.
function calculateSum() {
let div = document.getElementsByClassName("myParagraph");
let array = new Array;
for (var i = 0; i <div.length; i++) {
array.push(div[i].innerHTML);
}
let numberedArray = array.map((i) => Number(i));
const sumArray = numberedArray.reduce(function(a, b){
return a + b;
}, 0);
const createElement = document.createElement("div");
createElement.innerHTML = sumArray;
document.getElementById("divForAvg").appendChild(createElement);
}
And the last function that will change the innerHTML of the paragraph element when clicked.
function editELement() {
const input2 = document.getElementById("myInput2")
let items = document.getElementsByClassName("myParagraph");
for(var i = 0; i < items.length; i++){
items[i].onclick = function(){
items[i].innerHTML = input2.value;
}
}
}
So basically when I create some paragraphs and execute the second function, the second function will calculate the sum of the paragraphs and create a div with the sum inside.
What I want is when I remove one of the paragraph elements or edit them, I want the previously created divs to update(recalculate the sum), I have literally no idea on how to do this.
Let's try this using event delegation. I have interpreted what I think you are looking for (note: it's exemplary, but it may give you an idea for your code) and reduced your code a bit for the example. Note the 2 different ways to create new elements (insertAdjacentHTML and Object.assign).
You can play with the code #Stackblitz.com.
document.addEventListener("click", handle);
function handle(evt) {
if (evt.target.id === "create") {
return appendInputValueElement();
}
if (evt.target.classList.contains("remove")) {
return removeThis(evt.target);
}
if (evt.target.id === "clear") {
document.querySelector("#accumulated ul").innerHTML = "";
return true;
}
}
function appendInputValueElement() {
const input = document.querySelector(".myInput");
const div = document.querySelector("#exampleDiv");
exampleDiv.insertAdjacentHTML("beforeEnd", `
<div class="myDiv">
<button class="remove">remove</button>
<span class="myParagraph">${input.value || 0}</span>
</div>
`);
calculateSum();
}
function removeThis(elem) {
elem.closest(".myDiv").remove();
calculateSum();
}
function calculateSum() {
const allParas = [...document.querySelectorAll(".myParagraph")];
const sum = allParas.reduce( (acc, val) => acc + +val.textContent, 0);
document.querySelector("#accumulated ul")
.append(Object.assign(document.createElement("li"), {textContent: sum}));
document.querySelector(".currentSum").dataset.currentSum = sum;
if (sum < 1) {
document.querySelector("#accumulated ul").innerHTML = "";
}
}
.currentSum::after {
content: ' 'attr(data-current-sum);
color: green;
font-weight: bold;
}
.myParagraph {
color: red;
}
.accSums, .currentSum, .myDiv {
margin-top: 0.3rem;
}
<div>
A number please: <input class="myInput" type="number" value="12">
<button id="create">create value</button>
</div>
<div class="currentSum" data-current-sum="0">*Current sum</div>
<p id="exampleDiv"></p>
<div id="accumulated">
<div class="accSums">*Accumulated sums</div>
<ul></ul>
<button id="clear">Clear accumulated</button>
</div>
i've changed calculateSum you can call it when you edited paragraph. If summParagraph doesn't exists then we create it.
function calculateSum() {
let div = document.getElementsByClassName("myParagraph");
let array = new Array;
for (var i = 0; i <div.length; i++) {
array.push(div[i].innerHTML);
}
let numberedArray = array.map((i) => Number(i));
const sumArray = numberedArray.reduce(function(a, b){
return a + b;
}, 0);
if (!document.getElementById("summParagraph")) {
const createElement = document.createElement("div");
createElement.setAttribute("id", "summParagraph");
document.getElementById("divForAvg").appendChild(createElement);
}
document.getElementById("summParagraph").innerHTML = summArray;
}

Creating multiple spans in the same javascript function

var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function() {
var text = reader.result;
var output = document.getElementById('output');
const lines = text.split('\n');
lines.forEach((line) => {
const div = output.appendChild(document.createElement('div'));
const textSplitAroundAt = line.split('Microsoft');
textSplitAroundAt.forEach((text, i) => {
div.appendChild(document.createTextNode(text));
if (i === textSplitAroundAt.length - 1) return;
const span = div.appendChild(document.createElement('span'));
span.textContent = 'Microsoft';
span.className = 'colorMicrosoft';
});
});
document.getElementById('populateAt').textContent = text.split('#').length - 1;
document.getElementById('populateMicrosoft').textContent = text.split('Microsoft').length - 1;
document.getElementById('populateGoogle').textContent = text.split('Google').length - 1;
};
reader.readAsText(input.files[0]);
};
.colorMicrosoft
{
color: blue;
background-color: red;
}
.colorGoogle
{
color: red;
background-color: blue;
}
.colorAt
{
color: blue;
background-color: green;
}
<center>
<h1>.TXT Log Parser</h1>
</center>
<center>
<div>I would like the number of times '#' symbol appears here: <span id="populateAt"> ... </span></div>
<div>I would like the number of times 'Microsoft' symbol appears here: <span id="populateMicrosoft"> ... </span></div>
<div>I would like the number of times 'Google' symbol appears here: <span id="populateGoogle"> ... </span></div>
</center>
<center>
<h2><input type='file' accept='text/plain' onchange='openFile(event)'></h2>
</center>
<br/>
<div id='output'>...</div>
As long can see if the below code snippet, I am loading a text file into a div.
Currently I can tally the number of times a specific strings show up.
Additionally, I can change the color of each 'Microsoft' string via span.
However, I cannot seem to add multiple spans for 'Google' and '#'
Should I use an array, and if so, how?
You can check line for occurrence of each of three words, without using array
var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function() {
var text = reader.result;
var output = document.getElementById('output');
const lines = text.split('\n');
lines.forEach((line) => {
const div = output.appendChild(document.createElement('div'));
var textSplit = line.split('Microsoft');
line = textSplit.join('<span class="colorMicrosoft">Microsoft</span>');
textSplit = line.split('Google');
line = textSplit.join('<span class="colorGoogle">Google</span>');
textSplit = line.split('#');
line = textSplit.join('<span class="colorAt">#</span>');
div.innerHTML += line;
});
document.getElementById('populateAt').textContent = text.split('#').length - 1;
document.getElementById('populateMicrosoft').textContent = text.split('Microsoft').length - 1;
document.getElementById('populateGoogle').textContent = text.split('Google').length - 1;
};
reader.readAsText(input.files[0]);
};
.colorMicrosoft
{
color: blue;
background-color: red;
}
.colorGoogle
{
color: red;
background-color: blue;
}
.colorAt
{
color: blue;
background-color: green;
}
<center>
<h1>.TXT Log Parser</h1>
</center>
<center>
<div>I would like the number of times '#' symbol appears here: <span id="populateAt"> ... </span></div>
<div>I would like the number of times 'Microsoft' symbol appears here: <span id="populateMicrosoft"> ... </span></div>
<div>I would like the number of times 'Google' symbol appears here: <span id="populateGoogle"> ... </span></div>
</center>
<center>
<h2><input type='file' accept='text/plain' onchange='openFile(event)'></h2>
</center>
<br/>
<div id='output'>...</div>

Categories

Resources