'document.getElementById for a "div" alerting [object HTMLDivElement] instead of "thisDiv" [closed]
Why does my function alert [object HTMLDivElement]
instead of thisDiv
?
<div id="myId">thisDiv</div>
<script>
function x() {
var x1 = document.getElementById("myId");
alert(x1);
}
x();
</script>
Solution 1:[1]
<div id="myId">thisDiv</div>
<script>
function x() {
var x1 = document.getElementById("myId");
alert(x1.innerText);
}
x();
</script>
x1 is an HTML element and is displayed as such. To get "thisDiv"
, you have to extract text from it with innerText
.
Solution 2:[2]
Try to use textContent, like this.
<div id="myId">thisDiv</div>
<script>
function x() {
var x1 = document.getElementById("myId").textContent;
alert(x1);
}
x();
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | xxx |
Solution 2 | xxx |