TypeError: document.getElementById(...) is null Django + JS

Viewed 1074

I'm having an error while executing the following code:

var toppings = ['Zucchini', 'Fresh Garlic', 'Black Olives', 'Anchovies',
  'Barbecue Chicken', 'Artichoke', 'Spinach', 'Ham', 'Sausage', 'Mushrooms'];

var appended = 0;
var maxAppended = 3;

document.getElementById('add').onclick = () => {
  appended+=1;
  if(appended <= maxAppended){
  const topping = document.createElement('select', {
    'name': 'Topping',
    'class': 'form-control'
  });
  list.appendChild(topping);
  toppings.forEach(function(item, i, arr) {
    const ch_topping = document.createElement('option');
    ch_topping.innerHTML += item;
    topping.appendChild(ch_topping);
  });
  }
  else {
      alert('You should stop');
  }
};

page1.html:

 <div class="form-group" id='add_one'>
    <br>
    <h5>You can add up to 3 toppings to your pizza!</h5>
    <ol id="list"></ol>
    <button class="btn btn-primary" id="add" type="submit">Add topping</button>
  </div>

This code fails with the following error:

TypeError: document.getElementById(...) is null

I'm including JavaScript on my base.html file and page1.html extends this file.

My base.html <head>:

<title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
    <script src="{% static 'js/main.js' %}"></script>

window.onload() didn't help

jQuery's $(document).ready() didn't help

3 Answers

Your javascript file is running before the button exists in the DOM, so it can not find it

wrapper your code with use window.onload

whenever you access a DOM element, it must already be rendered

Perform a null checker

let button = document.getElementById('id');

if(typeof button !== 'undefined' && button !== null) {
  button.onclick = () => { /* Do your stuff */ };
}

Button's type="submit" must be eliminated if you want to add listener.

Related