Anytime you want to use JavaScript in WordPress, you should enqueue it.
Save the JS as a file, ie clickbutton.js
inside your theme folder:
document.getElementById("defaultOpen").click();
Then in functions.php
, enqueue that file:
add_action('wp_enqueue_scripts', 'wpse_371294_enqueue_js');
function wpse_371294_enqueue_js() {
wp_enqueue_script('click-button', get_template_directory_uri() . '/clickbutton.js', array(''), "1.0", true);
}
(If you only need the file to run on one page, enqueue it conditionally so it doesn’t get loaded elsewhere.)
However, note that you haven’t set any trigger for this to fire. For this type of JS to work, you will likely need to use a trigger such as
jQuery( document ).ready(function() {
document.getElementById("defaultOpen").click();
});
so that the code runs when the page loads fully. If you go that route, you’ll also need to make sure that you enqueue the script with jQuery as a dependency:
add_action('wp_enqueue_scripts', 'wpse_371294_enqueue_js');
function wpse_371294_enqueue_js() {
wp_enqueue_script('click-button', get_template_directory_uri() . '/clickbutton.js', array('jquery'), "1.0", true);
}
And on a final note, it’s likely you could achieve this same effect with CSS. Have whatever the button does load by default, use CSS to show it rather than hide it, and then if someone clicks to close use CSS to hide. It depends on exactly what you’re doing, but there’s often a way to avoid running JS for an initial page state.