Hello
Today, we will discuss the reason why a DOM method/ jQuery selector is unable to find an element.
There could possibily be following reasons for this behavior of the method/selector:
- The element with the ID passed does not actually exist. You need to check again to determine the accuracy of the passed ID. It can be mis-spelled as well.
- The element that is passed and being looked for is not present in the DOM at the time when the script ran.
- There are more than one elements with the same ID which causes conflict.
In order, to eliminate this problem one of these approaches can be followed:
Move the script down the page before closing the body tag. This is because the document is parsed from top to bottom. If the script is executed when it is encountered then it might not find the element that occurs later. It is considered a best practice to place all the scripts at the bottom.
Wait for DOM to be completely parsed. jQuery should be loaded properly. Make sure that the jQuery file is found with proper url. Put all the code that can affect the element passed inside a event handler. The event handler can be DOMContentLoaded or window.onload in case of javascript or ready() for jQuery.
$(document).ready(function() {
// when DOM is ready
});
Delayed events like on() can be used for elements that didnt exist at the load time.
<script>
$(document).on(click", #dropdown-div", function() {
alert(this.innerHTML);
});
</script>
<div id="dropdown-div>Demo Div</div>
We could also make use of the defer attribute of script in cases where the script being used has a src attribute i.e. the script is external.
0 Comment(s)