Cannot run script properly with my custom plugin

The question:

I’m pretty new with wordpress developing. What I’m trying to do is to add javascript to my plugin. It seems to be loaded, because when I’m console loging something like ‘test’ it works fine. But when I’m trying to query anything (for example document.querySelector(‘#only-for-test’)) or even (‘body’), it gives me back ‘null’…

function addThemeStyles() {
  wp_enqueue_style('style_file' , plugin_dir_url(__FILE__).'plugin_styles.css');

function addThemeScript() {
  wp_enqueue_script('js-file', plugin_dir_url(__FILE__).'plugin_pj_script.js');

function todoPJ_enqueueBootstrapCSS()
    // CSS
    wp_register_style('prefix_bootstrap', '//');

function testFunction() {
  // $test = plugin_dir_path('styles.css');

  return '
  <div class="another-test-file" id="only-for-test">
    <div class="container">
      <div class="row">
        <div class="col-6">
          <h1>Hello World!</h1>
        <div class="col-6">
          <h1>Another Hello World!</h1>

add_action('wp_enqueue_scripts', 'addThemeStyles');
add_action('wp_enqueue_scripts', 'addThemeScript');
add_action('wp_head', 'todoPJ_enqueueBootstrapCSS');

add_shortcode('example', 'testFunction');

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

I figured this out, maybe it will help someone – probably, my script was loading on the header, so html was loading after script fired. What I did was adding those few parameters, where this last ‘true’ is the most important (moves script to footer). Hope this helps to anyone

  wp_enqueue_script('js-file', plugin_dir_url(__FILE__).'/js/plugin_pj_script.js', '', '1.0.0', true);

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment