0

So I have a HTML file with an embedded script. A Java application sends a value to this HTML file. Now I wonder how to pass this value from the HTML down to the script. Is this even possible?

Here is the simplified HTML file with my approach:

<html>
  <body>
     <div id="test">
        [VALUE_FROM_BACKEND] // prints "let valueFromBackend = 1234"
     </div>

  <script>    
    console.log(document.getElementById('test').value);
    // should return: let valueFromBackend = 1234;
    // actually returns: undefined
  </script>

  </body>
</html>

Unfortunately, I can't pass the value from the Java application directly to the script. I got the above approach from here, but this doesn't work. Other solutions only focus on getting values from remote HTML pages, declaring the HTML files's source in the script tag. But since it is an embedded script here, this also seems not to work.

Does anyone know how to deal with the situation? Help will be much appreciated.

1
  • 1
    inputs have a value, divs do not. You could use .textContent to access the text. Commented Apr 29, 2020 at 10:42

2 Answers 2

1

Only HTML input elements have a value in javascript. A div cannot have a value, which is why your code returns undefined.

To access the text inside a regular HTML element, such as a div, use element.innerText instead.

Here is a working code snippet you can try out:

console.log(document.getElementById('test').innerText);
<div id="test">
  let valueFromBackend = 1234
</div>

Sign up to request clarification or add additional context in comments.

Comments

1

As you want to get value of a div element, so the syntax is: document.getElementById('test').innerHTML

Remember that getElementById().value works for input and use getElementById().innerHTML for elements like div

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.