Skip to content

How can I execute script after wordpress page contents fully loaded

I’m making a plugin for wordpress post page and I’m trying to detect div with id “matched”. I can see the div with browser tools, however console throws the message that the div wasn’t found. I think that’s because script is loading before the page contents. How can I make it to load after the post contents has rendered?

   <script type="text/javascript">

    var question =  document.getElementById("matched");

    window.onload = function afterWebPageLoad() { 
    
        if(question){
            console.log("id 'matched' exists");
        } else {
            console.log("id 'matched' not found");
        }

    }
</script>

Answer

You were calling document.getElementById before waiting for the page to load with the onload listener.

Move the variable declaration inside the onload listener so that it is only called when the page is loaded.

What your code should look like:

<script type="text/javascript">

  window.onload = function afterWebPageLoad() {
    var question = document.getElementById("matched"); // <-- Moved inside
    
    if (question) {
      console.log("id 'matched' exists");
    } else {
      console.log("id 'matched' not found");
    }
  }
  
</script>

<p id="matched">match element</p>