Home > Mobile >  Delete element in JS
Delete element in JS

Time:10-27

I was trying to prototype a site for a To-Do List to experiment with something new using JavaScript.

function task() {
  //Create checkbox
  var x = document.createElement("INPUT");
  x.setAttribute("type", "checkbox");

  //Create <br>
  lineBreak = document.createElement("br");

  //Create <p> element
  var todo = document.createElement("p");

  //Insert in <p> the text in the input box
  todo.innerText = document.getElementById("task").value;

  //Create the <p>checkbox text</p><br> on every botton click
  return document.body.appendChild(x)   document.body.appendChild(todo)   document.body.appendChild(lineBreak);

  document.querySelector('#reset').addEventListener('click', () => {
    document.getElementById('reset').clicked
  });
}

//Show Reset button on task generated
document.querySelector('#go').addEventListener('click', () => {
  document.getElementById("reset").style.visibility = "visible";
});
p {
  display: inline;
}

img {
  width: 30px;
  display: inline;
}

#reset {
  visibility: hidden;
}
<h1>To-Do List</h1>
<input type="text" placeholder="Write a Task" id="task"><button id="go" onclick="task()">GO</button>
<hr>

<body>
  <section>
    <button id="reset">RESET</button>
  </section>
</body>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

As you can see from the code and the indicated if statement I was able to generate for each click on the go button (defined in HTML) new <p></p>. It successfully generates a checkbox, next to a text typed in a text box and then wraps with the <br>.

I was trying to eliminate the elements generated by pressing the reset button, but despite having tried several solutions the only one that seems to work is the one that deletes all the contents of the body.

Could you suggest a solution to allow it to work?

CodePudding user response:

Just make the adjustments to your javascript code with the following steps and it should work as your expectation:

Steps to fix the code:

Step 1: AddEventListener should be called before return so it would be called whenever the task() is executed with the click of the Go button.

Step 2: Firstly, remove the className "go-element" from the previously added elements if they exist.

Step 3: Add the class "go-element" to newly added elements so they can be identified easily while resetting them.

Step 4: on reset click, it should remove all the elements with the class "go-element"

Note: If you just want to remove all the elements which are added through the Go button, just skip step 2. Also, to simplify you can wrap your all elements in a div element and just follow all the steps as shown above with the div instead of elements.

function task() {
  // Step 2: removing go-element class from previously added elements
  const elements = document.getElementsByClassName("go-element");
  while(elements.length > 0) {
    elements[0].classList.remove("go-element");
  }

  // Step 3: add the class name to new elements
  //Create checkbox
  var x = document.createElement("INPUT");
  x.setAttribute("type", "checkbox");
  x.classList.add("go-element"); //         step 3
  //Create <br>
  lineBreak = document.createElement("br");
  lineBreak.classList.add("go-element"); // step 3
  //Create <p> element
  var todo = document.createElement("p");
  todo.classList.add("go-element"); //      step 3
  //Insert in <p> the text in the input box
  todo.innerText = document.getElementById("task").value;

  // Step 1: moved this code before return so it will execute
  document.querySelector('#reset').addEventListener('click', () => {  
    // Step 4: removing elements with class name "go-element" 
    const elements = document.getElementsByClassName("go-element");
    while (elements.length > 0) {
      elements[0].parentNode.removeChild(elements[0]);
    }
  });

  //Create the <p>checkbox text</p><br> on every botton click
  return document.body.appendChild(x)   document.body.appendChild(todo)   document.body.appendChild(lineBreak);
}

//Show Reset button on task generated
document.querySelector('#go').addEventListener('click', () => {
  document.getElementById("reset").style.visibility = "visible";
});

CodePudding user response:

The main problem you have in your original code is that you are trying to create an eventListener after a return statement in the task function. Placing the return function at the end will allow you to add the event listener as intended, but I would advise moving the event listener outside of the task function to be called only once.

Most of the other changes I made in my code below were preferential changes, but I'll list a few things that will help you with this.


In the #reset element's event listener, you want to clear the tasks. There are a few ways this can be done, but most of which involve modifying the inserted elements to be sure you're only deleting the elements you intend to. You're already using a paragraph <p> tag, so that is an excellent choice for wrapping the checkbox and the task item text together (you could also use a list item <li> tag and wrap the whole list in an unordered list <ul> or and ordered list <ol> tag).

Example of a task after adding it to the list:

<p><input type="checkbox" />task item</p>

As for handling the reset, you want to wrap the whole list in a container element, such as the section element you have in your code already. This does involve moving the reset button out so that we do not remove it from the DOM:

<button id="reset">RESET</button>
<section id="tasklist"></section>

Now, when the reset event handler is called, you can use .innerHTML = "" to clear the list.


Additionally, I removed the onclick attribute from the GO button in the HTML and added it to the event handler in the JavaScript.

<button class="hidden" id="reset">RESET</button>
goButton.addEventListener("click", () => {
  resetButton.classList.remove("hidden");
  task();
});

I also added in a few helpful features, such as creating the necessary elements once and cloning using Node.cloneNode(), setting references to the static elements needed in the script, and creating labels with unique IDs of the checkboxes so that selecting the text will select the checkbox (helpful for accessibility, but up to you as to whether you need it).

// Set up references to all static elements to reduce DOM calls
const taskInput = document.getElementById("task");
const resetButton = document.getElementById("reset");
const goButton = document.getElementById("go");
const taskList = document.getElementById("tasklist");

// Create instances of elements to clone with Node.cloneNode()
const checkboxInput = document.createElement("input");
const taskLabel = document.createElement("label");
const lineBreak = document.createElement("br");
const paragraph = document.createElement("p");

// Set any attributes needed
checkboxInput.setAttribute("type", "checkbox");

// Keep track of our unique ids
var count = 0;

function task() {
  /** Get the value of count (increment after) and return as
    * a 2-digit string padded with leading zeroes */
  const id = `todo-${String(count  ).padStart(2, "0")}`;
  //Create checkbox
  var x = checkboxInput.cloneNode();
  x.id = id;
  x.addEventListener("change", function(event) {
    event.target.parentElement.remove();
  });

  //Create label for the task
  var label = taskLabel.cloneNode();
  label.innerText = taskInput.value;
  label.setAttribute("for", id);

  //Create <p> element
  var todo = paragraph.cloneNode();
  todo.appendChild(x);
  todo.appendChild(label);

  //Create the <p><label>checkbox</label>text</p> on every botton click
  taskList.appendChild(todo);
}

//Show Reset button on task generated
goButton.addEventListener("click", () => {
  resetButton.classList.remove("hidden");
  task();
});

// Set the "click" event listener and handle it as intended
resetButton.addEventListener("click", () => {
  count = 0;
  taskList.innerHTML = "";
  resetButton.classList.add("hidden");
});
input[type=checkbox] {
  margin-right: 0.5rem;
}

p {
  border: 1px solid green;
}

.hidden {
  display: none;
}
<h1>To-Do List</h1>
<section><input type="text" placeholder="Write a Task" id="task"></section>
<section><button id="go">GO</button> <button class="hidden" id="reset">RESET</button>
</section>
<hr>
<section id="tasklist"></section>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Take a Look at the jquery Handlers to watch the Button: https://api.jquery.com/click/

   $( "#reset" ).click(function() {
     $('#something').remove();
   });

And I am not sure what 'element' is. It is not defined in the snippet.

  • Related