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
You were calling
document.getElementById
before waiting for the page to load with theonload
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:
You can use
setInterval
like this;Also, you must check the element in
afterWebPageLoad
function. You must move question variable to the function.