Access HTML of WP Plugin (PHP) function with CSS an JS

Note to the mods: Because there are several languages involved here, I didn’t know where to post it.

Problem:

My Goal is to insert HTML code with my WP shortcode function (PHP) and change the background from these HTML elements by using JavaScript from the plugin.

I’ve been looking all day for a solution by google and watch videos but can’t find the solution.

Questions:

How do I make the JavaScript and CSS recognize the HTML code of the shortcode? My JavaScript is not executed. Chrome gives me “Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)”

Is it possible that the HTML code is not saved in the document DOM because it is only added by the plugin? (It’s my first try for a WP plugin)

PHP & HTML

<?php
/** 
 * Plugin Name: Own Wordpress Plugin
 * Description: A Test Plugin for Wordpress
 * Version: 1.0.0
*/

//Add Shortcode
add_shortcode( 'my_shortcode', 'my_function');
function my_function() {
    return '
    <button id="my-btn">Change Background</button>
    <div id="box">
        <p>Any Text</p>
    </div>';
}

//Add CSS and JS
add_action( 'wp_enqueue_scripts', 'my_scripts');
function my_scripts() {
    wp_enqueue_style("my_plugin_style", plugins_url( 'style.css', __FILE__ ));
    wp_enqueue_script("my_plugin_js", plugins_url( 'script.js', __FILE__));
}

JS

const box = document.getElementById("box")
const myBtn = document.getElementById("my-btn")

myBtn.addEventListener("click", changeBackground)
function changeBackground() {
    box.style.backgroundColor = "green"
}

CSS

#box{
    background-color: red;
}

I would be very happy if you can give me a tip/solution or a link.

Not sure what the proper WP way of doing it is but if you set $in_footer to true it should load it after the page content.

Or you can try wrapping the JS code inside a DOMContentLoaded event handler.

1 Like

Thanks a lot! With in_footer it works!