1
    $('#submit').on('click', function(){

      $.ajax({
        type:'GET',
        url:'http://www.boredapi.com/api/activity/',
        success: function(data){// my data
            console.log(data);
            console.log(data.activity);
            
            var body = document.getElementById('add');
            var newDiv = document.createElement('div');
            
            newDiv.innerText = data.activity;
            console.log(newDiv); //my data
            console.log(body); 
            var num = 0;
            
            body.appendChild(newDiv);
          
            $('#submit').on('click', function(){
                body.removeChild(newDiv);
            
            
    })   
  }              
})

})

I am trying to add one div with one click, and with a second click remove the first div and add a new div in its place. Right now, I figured out a way to have another eventListner to make a second 'click' remove the first div and add a second but the third click it'll go right back to storing every div with each click. I thing a loop between both eventListner will work but not sure how to make that work logically. I hope I've explained this well enough. Thank you in advance for your help.

Lj32404
  • 11
  • 2

5 Answers5

0
$('#submit').on('click', function(){
    
    $.ajax({
        type:'GET',
        url:'http://www.boredapi.com/api/activity/',
        success: function(data){// my data
            console.log(data);
            console.log(data.activity);
            
            var body = document.getElementById('add');
            var newDiv = document.createElement('div');
            
            newDiv.innerText = data.activity;
            console.log(newDiv); //my data
            console.log(body);
            $("#add").empty()
            
            body.appendChild(newDiv);
          
        }
Lj32404
  • 11
  • 2
0

You can use replaceWith() in this case: Like:

var body = document.getElementById('add');
var newDiv = document.createElement('div');
var old_div = document.querySelectorAll('#add>div') !== null;

if(!old_div){
    body.appendChild(newDiv);
} else {
    old_div.replaceWith(newDiv);
}

If third line is not understandable, see here.

Overall, your code will look sthg like this:

$.ajax({
        type:'GET',
        url:'http://www.boredapi.com/api/activity/',
        success: function(data){// my data
            console.log(data);
            console.log(data.activity);
            
            var body = document.getElementById('add');
            var newDiv = document.createElement('div');
            var old_div = document.querySelectorAll('#add>div') !== null;
            
            newDiv.innerText = data.activity;

            if(!old_div){
                body.appendChild(newDiv);
            } else {
                old_div.replaceWith(newDiv);
            }        
            
    })   
  }              
})

*Note:- success, error, complete are depreciated are removed from version 3.0. Refs

Biplove Lamichhane
  • 3,995
  • 4
  • 14
  • 30
0

You need to check if the div exists before removing it. The first time the form is submitted there is no div, so it's going to be created and then the new click event will be binded. Then when you click again that div already exists, so you are creating it again, before removing the previous one. I suggest you to add an id to the div in the moment you create it

I would do:

$('#submit').on('click', function () {

  $.ajax({
    type: 'GET',
    url: 'http://www.boredapi.com/api/activity/',
    success: function (data) {
      var body = $('#add');

      if($('#NewDiv')){
        body.removeChild($('#NewDiv'))
      }


      // my data
      console.log(data);
      console.log(data.activity);

      var newDiv = $(document.createElement('div'));
      
      newDiv.attr('id', 'NewDiv');
      newDiv.innerText = data.activity;
      console.log(newDiv); //my data
      console.log(body);
      var num = 0;

      body.appendChild(newDiv);

    }
    })
  })
KarlsMaranjs
  • 311
  • 1
  • 9
0

This solution stores newDiv and ensures that it's not null before it's removed:

<script>
    var newDiv = null;
    var body = document.getElementById('add');

    $('#submit').on('click', function () {
        if (newDiv) {
            body.removeChild(newDiv);
        }

        $.ajax({
            type: 'GET',
            url: 'http://www.boredapi.com/api/activity/',
            success: function (data) {// my data
                console.log(data);
                console.log(data.activity);
                
                newDiv = document.createElement('div');
                newDiv.innerText = data.activity;
                
                console.log(newDiv); //my data
                console.log(body);
                var num = 0;

                body.appendChild(newDiv);
            }
        })
    });
</script>
Andrew Arthur
  • 1,563
  • 2
  • 11
  • 17
0

Here is a solution on how you can remove and append divs using clicks, I have added a counter to demonstrate the change, you can accustom this solution to fit your need

let body = document.getElementById('add');
let olddiv = document.getElementById('olddiv');
let divs=document.getElementsByClassName("div");
flag = false
counter = 0
$('#submit').on('click', function() {

  if (!flag) {
    addiv(counter)
    console.log("divadded ",divs)
    counter++
    flag = true

  } else {
    addNewDiv(counter)
    counter++
    flag = false

  }

})

function addiv(counter) {
  while (body.hasChildNodes()) {
    body.removeChild(body.firstChild);
  }
  var newDiv = document.createElement('div');
  newDiv.id = `olddiv${counter}`
 newDiv.className = "div"

  newDiv.innerText = counter;
  body.appendChild(newDiv);

}

function addNewDiv(counter) {
  while (body.hasChildNodes()) {
    body.removeChild(body.firstChild);
  }
  addiv(counter)
  console.log("removed",divs)

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="add"></div>

<button id="submit">changeDiv</button>
Sven.hig
  • 4,449
  • 2
  • 8
  • 18