Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementById().value return undefined in chrome

Tags:

javascript

<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?

like image 273
run Avatar asked May 22 '12 01:05

run


People also ask

What will method getElementById () return if nothing is found?

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.

Why is getElementById returning NULL?

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.

What does the document getElementById () method return?

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.


2 Answers

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;
like image 102
nnnnnn Avatar answered Sep 20 '22 08:09

nnnnnn


document.getElementById("hour").innerText

or

document.getElementById("hour").innerHTML
like image 34
neohope Avatar answered Sep 20 '22 08:09

neohope