Search code examples
javascriptappendchild

Console error with append child when element doesn't exist


I have the following code inside a timeout function which works fine when the element exists, but when it doesn't, it throws a console error (and is breaking something else on the page as a result)

setTimeout(function() {
  // moves #dashboard_basket_btn into #dashboard_basket
  var dashboard_basket = document.querySelector('#dashboard_basket');
  var dashboard_basket_card = document.querySelector('#dashboard_basket_btn');
  dashboard_basket.appendChild(dashboard_basket_card);
  dashboard_basket_card.classList.add('show_important');
}, 2500);

When #dashboard_basket_btn doesn't exist (it's sometimes loaded in dynamically, not always on usual page load), the part of the appendChild function where it references dashboard_basket_card says that parameter 1 is not of type: Node (guessing that means it doesn't exist?)

Is there a clever way of handing this or for it not to get upset if the element doesn't exist at the time the function runs?


Solution

  • At first you can check whether the element exists or not, For example

    var dashboard_basket_card_exists = document.querySelector('#dashboard_basket_btn') !== null; //the value will be true if it exists or false, if it isn't.
    
    var dashboard_basket_exists = document.querySelector('#dashboard_basket') !== null;
    
    

    After that, you can write a regular if statement, Like

    if(dashboard_basket_card_exists && dashboard_basket_exists)
    {
     var dashboard_basket = document.querySelector('#dashboard_basket');
     var dashboard_basket_card = document.querySelector('#dashboard_basket_btn');
     dashboard_basket.appendChild(dashboard_basket_card);
     dashboard_basket_card.classList.add('show_important');
    }
    
    

    This is one way to solve this issue.