I've created a variable named btn which I'm assigning to a document.querySelector() function. The query selection seems correct as it successfully grabs the desired element when tested in the browser console. However, the assignment returns null. Could this be due to limitations within the osclass framework when trying to access HTML elements in this manner?
Currently, I'm developing a plugin that modifies the registration form by adding a text field with an event listener to monitor input changes. If there is input detected, I want the form to perform an action upon clicking the submit button. Identifying the newly added form field poses no issues, possibly because it's part of the plugin directory. On the other hand, accessing HTML from the theme proves to be challenging. This may be partly attributed to attempting to retrieve it before the complete HTML content loads. Despite my attempts to defer the script and employ inline code execution post-DOM load, success remains elusive.
The specific section of HTML I aim to target is:
<div class="controls">
<button type="submit" class="ui-button ui-button-middle ui-button-main"><?php _e("Create", 'bender'); ?></button>
</div>
Provided below is both the code snippet utilized for retrieval and the intended code block for execution:
var btn = document.querySelector("div.controls button");
btn.addEventListener("submit", function() {
console.log("Honey is sweet!");
});
Lastly, here's how the script is invoked:
<script type="text/javascript" async="" defer="" src="<?php echo osc_base_url().'oc-content/plugins/honeypot/fieldcheck.js';?>"></script>
It's worth noting that I'm executing this as a function using the osclass hook:
osc_add_hook('user_register_form', 'twf_honeypot_form_field');
The expected outcome involves the variable capturing the button and linking an event listener to it. Upon submission of the form, a message should be logged in the console. However, instead of the desired behavior, an error is thrown: Uncaught TypeError: Cannot read property 'addEventListener' of null.
For those familiar with osclass, could this issue stem from the HTML residing elsewhere? My assumption was that deferring the script would delay its execution until page loading completed, thus allowing HTML extraction. If not, what approach should I take to extract this specific HTML fragment from a theme file?