0

i'm trying to obtain the value of an element with javascript but i'm getting undefined as it's value even if i know it isn't.

<!DOCTYPE html>
<html>
<body>

<p>Click "Try it" to display the first array element, after a string split.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var str = "a,b,c,d,e,f";
    var arr = str.split(",");
    document.getElementById("demo").innerHTML= arr[0];
    alert(document.getElementById("demo").value);
}
</script>

</body>
</html>

How can i obtain the value of "demo" once i changed it?

1 Answers1

2

You are actually setting the innerHTML attribute of the #demo element, not value.

function myFunction() {
    var str = "a,b,c,d,e,f";
    var arr = str.split(",");
    document.getElementById("demo").innerHTML = arr[0];
    alert(document.getElementById("demo").innerHTML);
}
<p>Click "Try it" to display the first array element, after a string split.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
kind user
  • 40,029
  • 7
  • 67
  • 77