Home > Software engineering >  How to clear content created from js?
How to clear content created from js?

Time:12-14

I'm trying to fix a problem where I have two inputs and after the user inserts two numbers (the first for word length and the second for word count), those words and their object values will appear in the HTML tab. Can't find a way to clear content generated with JS. In this case, I'm creating an HTML element and its content, but I'm unable to clear them after calling my function again, so the table's content is incremented.

tried to use replaceChildren() but didn't help.

let contentDiv = document.querySelector('.content')
let objectsArr = []

function wordsCreation() {
  const symbolsNumber = Number(document.querySelector('#symbol').value);
  const wordsNumber = Number(document.querySelector('#word').value);
  const lettersArr = 'abcdefghijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ';
  const vowelsArr = ['a', 'e', 'i', 'o', 'u'];

contentDiv.innerHTML = ''


  for (let i = 0; i < wordsNumber; i  ) {
    let createdWord = ''
    let lowerCase = 0;
    let uppererCase = 0;
    let vowel = 0;
    let consonant = 0;
    for (let counter = 0; counter < symbolsNumber; counter  ) {
      let randomLetter = lettersArr[parseInt((Math.random() * 52))];
      // დაითვლის მაღალი და დაბლი რეგისტრის ასოებს
      randomLetter != randomLetter.toLowerCase() ? uppererCase   : lowerCase  ;
      // დაითვლის ხმოვნებს და თანხმოვნებს
      for (let i of vowelsArr) {
        if (randomLetter == i || randomLetter.toLowerCase() == i) {
          vowel  
        }
      }
      createdWord  = randomLetter
    }
    consonant = createdWord.length - vowel

    let createdTag = document.createElement('p')

    if (vowel > consonant) {
      createdTag.style.color = 'red'
    } else if (vowel < consonant) {
      createdTag.style.color = 'blue'
    } else {
      createdTag.style.color = 'green'
    }

    createdTag.innerText = createdWord
    contentDiv.appendChild(createdTag)

    let emptyObject = {
      'word': `${createdWord}`,
      'vowel': `${vowel}`,
      'consonant': `${consonant}`,
      'uppererCase': `${uppererCase}`,
      'lowerCase': `${lowerCase}`
    }

    objectsArr.push(emptyObject)

  }

  let tableRowCounter = objectsArr.length
  let tableDataCounter = Object.keys(objectsArr[0]).length
  let table = document.createElement('table')
  contentDiv.appendChild(table)


  for (let a = 0; a < 1; a  ) {
    let tr = document.createElement('tr')
    for (let b = 0; b < tableDataCounter; b  ) {

      let th = document.createElement('th')
      th.innerText = Object.keys(objectsArr[a])[b]
      tr.appendChild(th)
    }
    table.appendChild(tr)
  }

  for (let a = 0; a < tableRowCounter; a  ) {
    let tr = document.createElement('tr')
    for (let b = 0; b < tableDataCounter; b  ) {

      let td = document.createElement('td')
      td.innerText = Object.values(objectsArr[a])[b]
      tr.appendChild(td)
    }

    table.appendChild(tr)
  }

}
body {
  background-color: rgb(9, 9, 34);
  color: white;
  font-size: 1.5rem;
}

table,
th,
td {
  border: 1px solid white;
  border-collapse: collapse;
}
<div >
  <label for="symbol">სიმბოლოების რაოდენობა</label>
  <input type="text" name="" id="symbol">
  <br>
  <label for="word">სიტყვების რაოდენობა</label>
  <input type="text" name="" id="word">
  <br>
  <button onclick="wordsCreation()">Generate to Table</button>
  <div ></div>
</div>

CodePudding user response:

You just need to move the let objectsArr = []; declaration inside the function.

let contentDiv = document.querySelector('.content')
// let objectsArr = []; // <== Cut from here...

function wordsCreation() {
  let objectsArr = []; // <== ...Move here
  const symbolsNumber = Number(document.querySelector('#symbol').value);
  const wordsNumber = Number(document.querySelector('#word').value);
  const lettersArr = 'abcdefghijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ';
  const vowelsArr = ['a', 'e', 'i', 'o', 'u'];

contentDiv.innerHTML = ''


  for (let i = 0; i < wordsNumber; i  ) {
    let createdWord = ''
    let lowerCase = 0;
    let uppererCase = 0;
    let vowel = 0;
    let consonant = 0;
    for (let counter = 0; counter < symbolsNumber; counter  ) {
      let randomLetter = lettersArr[parseInt((Math.random() * 52))];
      // დაითვლის მაღალი და დაბლი რეგისტრის ასოებს
      randomLetter != randomLetter.toLowerCase() ? uppererCase   : lowerCase  ;
      // დაითვლის ხმოვნებს და თანხმოვნებს
      for (let i of vowelsArr) {
        if (randomLetter == i || randomLetter.toLowerCase() == i) {
          vowel  
        }
      }
      createdWord  = randomLetter
    }
    consonant = createdWord.length - vowel

    let createdTag = document.createElement('p')

    if (vowel > consonant) {
      createdTag.style.color = 'red'
    } else if (vowel < consonant) {
      createdTag.style.color = 'blue'
    } else {
      createdTag.style.color = 'green'
    }

    createdTag.innerText = createdWord
    contentDiv.appendChild(createdTag)

    let emptyObject = {
      'word': `${createdWord}`,
      'vowel': `${vowel}`,
      'consonant': `${consonant}`,
      'uppererCase': `${uppererCase}`,
      'lowerCase': `${lowerCase}`
    }

    objectsArr.push(emptyObject)

  }

  let tableRowCounter = objectsArr.length
  let tableDataCounter = Object.keys(objectsArr[0]).length
  let table = document.createElement('table')
  contentDiv.appendChild(table)


  for (let a = 0; a < 1; a  ) {
    let tr = document.createElement('tr')
    for (let b = 0; b < tableDataCounter; b  ) {

      let th = document.createElement('th')
      th.innerText = Object.keys(objectsArr[a])[b]
      tr.appendChild(th)
    }
    table.appendChild(tr)
  }

  for (let a = 0; a < tableRowCounter; a  ) {
    let tr = document.createElement('tr')
    for (let b = 0; b < tableDataCounter; b  ) {

      let td = document.createElement('td')
      td.innerText = Object.values(objectsArr[a])[b]
      tr.appendChild(td)
    }

    table.appendChild(tr)
  }

}
body {
  background-color: rgb(9, 9, 34);
  color: white;
  font-size: 1.5rem;
}

table,
th,
td {
  border: 1px solid white;
  border-collapse: collapse;
}
<div >
  <label for="symbol">სიმბოლოების რაოდენობა</label>
  <input type="text" name="" id="symbol">
  <br>
  <label for="word">სიტყვების რაოდენობა</label>
  <input type="text" name="" id="word">
  <br>
  <button onclick="wordsCreation()">Generate to Table</button>
  <div ></div>
</div>

CodePudding user response:

You can clear the HTML and the array with one function that you call at the beginning of the wordsCreation()

function clearContent() {
  contentDiv.innerHTML = '';
  objectsArr = [];
}

You can also add a button to clear the content (but this is iptional), like:

<button onclick="clearContent()">Clear Content</button>

An additional note, I changed the content div to be identifiable by an ID (instead of class) since IDs are supposed to be unique. Querying the div by class will give you errors if you end up with more than one element with the same class name (i.e. <p >) since the following code assumes only one item (contentDiv) will be found.

let contentDiv = document.getElementById("content");
let objectsArr = []

function clearContent() {
  contentDiv.innerHTML = '';
  objectsArr = [];
}


function wordsCreation() {
  clearContent();
  
  const symbolsNumber = Number(document.querySelector('#symbol').value);
  const wordsNumber = Number(document.querySelector('#word').value);
  const lettersArr = 'abcdefghijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ';
  const vowelsArr = ['a', 'e', 'i', 'o', 'u'];

  for (let i = 0; i < wordsNumber; i  ) {
    let createdWord = ''
    let lowerCase = 0;
    let uppererCase = 0;
    let vowel = 0;
    let consonant = 0;
    for (let counter = 0; counter < symbolsNumber; counter  ) {
      let randomLetter = lettersArr[parseInt((Math.random() * 52))];
      // დაითვლის მაღალი და დაბლი რეგისტრის ასოებს
      randomLetter != randomLetter.toLowerCase() ? uppererCase   : lowerCase  ;
      // დაითვლის ხმოვნებს და თანხმოვნებს
      for (let i of vowelsArr) {
        if (randomLetter == i || randomLetter.toLowerCase() == i) {
          vowel  
        }
      }
      createdWord  = randomLetter
    }
    consonant = createdWord.length - vowel

    let createdTag = document.createElement('p')

    if (vowel > consonant) {
      createdTag.style.color = 'red'
    } else if (vowel < consonant) {
      createdTag.style.color = 'blue'
    } else {
      createdTag.style.color = 'green'
    }

    createdTag.innerText = createdWord
    contentDiv.appendChild(createdTag)

    let emptyObject = {
      'word': `${createdWord}`,
      'vowel': `${vowel}`,
      'consonant': `${consonant}`,
      'uppererCase': `${uppererCase}`,
      'lowerCase': `${lowerCase}`
    }

    objectsArr.push(emptyObject)

  }

  let tableRowCounter = objectsArr.length
  let tableDataCounter = Object.keys(objectsArr[0]).length
  let table = document.createElement('table')
  contentDiv.appendChild(table)


  for (let a = 0; a < 1; a  ) {
    let tr = document.createElement('tr')
    for (let b = 0; b < tableDataCounter; b  ) {

      let th = document.createElement('th')
      th.innerText = Object.keys(objectsArr[a])[b]
      tr.appendChild(th)
    }
    table.appendChild(tr)
  }

  for (let a = 0; a < tableRowCounter; a  ) {
    let tr = document.createElement('tr')
    for (let b = 0; b < tableDataCounter; b  ) {

      let td = document.createElement('td')
      td.innerText = Object.values(objectsArr[a])[b]
      tr.appendChild(td)
    }

    table.appendChild(tr)
  }

}
body {
  background-color: rgb(9, 9, 34);
  color: white;
  font-size: 1.5rem;
}

table,
th,
td {
  border: 1px solid white;
  border-collapse: collapse;
}
<div >
  <label for="symbol">სიმბოლოების რაოდენობა</label>
  <input type="text" name="" id="symbol">
  <br>
  <label for="word">სიტყვების რაოდენობა</label>
  <input type="text" name="" id="word">
  <br>
  <button onclick="wordsCreation()">Generate to Table</button>
  <button onclick="clearContent()">Clear Content</button>

  <div id="content"></div>
</div>

  • Related