<div id="hour" style="display: none">2</div>
JavaScript code:
<script type="text/javascript">
var _h = document.getElementById('hour').value
alert(_h);
</script>
Chrome returns undefined
. What is the problem?
The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM.
This error TypeError: document. getelementbyid(...) is null would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element.
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
The .value
property applies to form elements (inputs), not divs. The simplest way to get the contents of your div element is with .innerHTML
:
document.getElementById('hour').innerHTML;
document.getElementById("hour").innerText
or
document.getElementById("hour").innerHTML
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With