Junior
What is the <output> element in HTML5?
sobes.tech AI
Answer from AI
The <output> element is used to display the results of calculations, typically performed on the client side.
Examples of usage:
-
Binding with form elements:
<!-- Declare input for number input --> <input type="number" id="a" name="a" value="10"> + <!-- Declare input for another number --> <input type="number" id="b" name="b" value="20"> = <!-- Declare output to display result, linked with inputs by id --> <output name="result" for="a b"></output> <script> // Get input elements const a = document.getElementById('a'); const b = document.getElementById('b'); // Get output element const result = document.querySelector('output[name="result"]'); // Function to update result function updateResult() { // Perform calculation and update output value result.value = parseInt(a.value) + parseInt(b.value); } // Add event listeners to update result on input change a.addEventListener('input', updateResult); b.addEventListener('input', updateResult); // Initial update on page load updateResult(); </script> -
Displaying JavaScript results:
<!-- Output element for displaying result --> <output id="message"></output> <script> // Get output element const messageOutput = document.getElementById('message'); // Set output value messageOutput.value = "Hello, world!"; // Or innerText messageOutput.innerText = "Hello, world!"; </script>
Attributes:
for: List of IDs of elements involved in calculation, whose result is displayed in<output>. Separated by spaces.name: Name of the<output>element. Used for form submission identification.
Important features:
- By default,
<output>has no visible content until itsvalueattribute or JavaScript sets it. <output>can be linked to form elements, but it is not part of the submitted form data unless itsvalueis set. Its value is usually updated dynamically via JavaScript.- Semantically, it is meant for outputting results, which is useful for accessibility and SEO.