简体   繁体   中英

how to check if multiple elements exist in JavaScript/Flask

I have a js file with button click event listeners. The problem is those buttons do not exist until flask sends the data over. I want to only run the listeners if the elements exists or when the elements exist.

I am trying to solve this error that occurs:

Uncaught TypeError: Cannot read property 'addEventListener' of null

HTML file:

<html>
  <body>
    {% if var %}
        <div>
         <h1>Hello {{var}}</h1>
         <button id="1">Click me</button>
         <button id="2">Click me</button>
         <button id="3">Click me</button>
         <button id="4">Click me</button>
        </div>
    {% endif %}
    <script async src="{{ url_for('static', filename='js/buttons.js') }}"></script>
  </body>
<html>

JS file:

var Btn1Element = document.getElementById("1");
var Btn2Element = document.getElementById("2");
var Btn3Element = document.getElementById("3");
var Btn4Element = document.getElementById("4");

Btn1Element.addEventListener(
  "click",
  () => {
      window.location = "/1";
  },
  false
);

Btn2Element.addEventListener(
  "click",
  () => {
      window.location = "/2";
  },
  false
);

Btn3Element.addEventListener(
  "click",
  () => {
      window.location = "/3";
  },
  false
);

Btn4Element.addEventListener(
  "click",
  () => {
      window.location = "/4";
  },
  false
);

With async attribute on script, a script that will be run asynchronously as soon as it is available while the page continues the parsing.

It needs to wait and run after page loaded for document.getElementById()

Try to update as like:

document.addEventListener("DOMContentLoaded", function() {
  // your js code on here
  var Btn1Element = document.getElementById("1");
  ...
});

or you could remove async attribute on script tag.

EDITED:

check whether {% if var %} is true on your context.

i think it is not about javascript. html tags(elements) do not created by flask view engine by if condition.

live on here and you could check what is different from yours

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM