document.getElementById().value return undefined in chrome

document.getElementById().value return undefined in chrome

本文关键字:undefined in chrome return value getElementById document      更新时间:2023-09-26
<div id="hour" style="display: none">2</div>

JavaScript 代码:

<script type="text/javascript">
    var _h = document.getElementById('hour').value
    alert(_h);
</script>

铬返回undefined .问题出在哪里?

.value 属性适用于表单元素(输入(,而不是div。获取div 元素内容的最简单方法是使用 .innerHTML

document.getElementById('hour').innerHTML;
document.getElementById("hour").innerText

document.getElementById("hour").innerHTML
div

没有值。它不是输入。

你想使用 innerHTML 或 innerText/textContent。

使用

document.getElementById() method for displaying text on google console. 
    

正如另一个OP所说,div没有.value属性。

您可以在此链接中看到所有HTML DOM属性:https://www.w3schools.com/JSREF/DEFAULT.ASP

<input id="hour" style="display: none" value="0" >

这应该可以消除错误。