-1

How show the content let text: string in tag

using typescript and getElementById?

Code index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./index.js"></script>
</head>
<body>
    <h1>Exercice typescript</h1>
    <p id="text">Text: </p>
</body>
</html>

Code index.ts

let text: string = 'Exercice typescript';
let textAuth = document.getElementById("text") as HTMLElement | null

Study
  • 85
  • 1
  • 3
  • 8
  • Does this answer your question? [How do I change the text of a span element using JavaScript?](https://stackoverflow.com/questions/1358810/how-do-i-change-the-text-of-a-span-element-using-javascript) – Quentin Aug 22 '22 at 19:06

1 Answers1

1

Because the element might be null, you need to first perform a conditional check to ensure that it exists before updating its text content. If you want to append to the text content, you also must check to be sure that the presumed text content exists:

See also Node.textContent - Web APIs | MDN

TS Playground

let text = 'Exercice typescript';
let textAuth = document.getElementById('text');
if (textAuth?.textContent) textAuth.textContent += text;
<h1>Exercice typescript</h1>
<p id="text">Text: </p>
jsejcksn
  • 27,667
  • 4
  • 38
  • 62