Beginner - JS querySelector on button

I’m a new Dash user and I’m trying to use a JS script in my Dash App:
I simply can’t querySelect the button.

import dash
import dash_html_components as html

app = dash.Dash(name)

app.layout = html.Div([
html.Button(‘Button 1’, id=‘btn’),


if name == ‘main’:


let a = document.querySelector(’#react-entry-point’)

let b = document.querySelector(’#btn’)


console.log(a) gives Element
console.log(b) gives null

Running document.querySelector(’#btn’) manually in chrome dev tools I get the element.

Can someone please explain why this happens?

Thanks a lot!

Been there myself recently as a person with vanilla JS backgrond. The question/hint is in the way you execute your JS code. Did you just drop a file in assets folder with the content as you described?
Then it executes before button exists. You may notice that when you open Dash app it goes into loading state first. So in your JS script you need to execute the code after the page has been loaded. You can use events for this or write some code with setInterval function to wait for the button to appear.

Thanks fralik! Thats it.

Using setInterval, the JS script works fine, (I just drop the js file in assets) . Example:


let interval = setInterval(function () {
  if (document.readyState === 'complete') {
}, 100);

function myMain() {
  let a = document.querySelector('button#btn');
  console.log("Document loaded....", a); = "blue";

For post completeness, can someone post a “use events” code sample or any way in dash to define that the JS script in assets is executed after the page is loaded?

Thank you all.

in my mind, you are using events in your code - ready state. A different approach is to query the element and check the result for null.

Notice also that Dash can recreate your button. So, if you are going to use a later, it may be invalid. As far as I remember, if button is affected by a callback, then it will be recreated.

Thank you very much.