skip to Main Content

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>

2

Answers


  1. 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>
    Login or Signup to reply.
  2. You can use setInterval like this;

    let checker = setInterval(function () {
        if (document.getElementById("matched") !== null) {
            console.log("found")
            clearInterval(checker)
        } else {
            console.log("checking..")
        }
    }, 100)
    

    Also, you must check the element in afterWebPageLoad function. You must move question variable to the function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search