Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 19, 2024 › #Element #HowTo

How can get the text of a div tag using JavaScript only

How to Retrieve the Text of a <div> Tag Using JavaScript? This blog post will guide you through the process of achieving this task step-by-step. We will provide a solution to the problem of getting undefined as the result and offer a clear explanation along with supporting code snippets.

Problem #

Consider the following code snippet.

function test() {
  let t = document.getElementById('my-container').value;
  alert(t);
}

When calling the test() function, you might expect it to retrieve the text content of the <div> element with the ID my-container and display it in an alert. However, it displays undefined instead.

Solution #

To retrieve the text content of a <div> tag, you should use the innerText property instead of value.
function test() {
  let t = document.getElementById('my-container').innerText;
  alert(t);
}

The innerText property returns the visible text within an element, stripping away any HTML tags and preserving only the textual content.

  1. In JavaScript, the getElementById() function allows you to access an element by its unique ID.
  2. The innerText property retrieves the text content of the specified element.
  3. By assigning the value of innerText to the variable t, we store the retrieved text content.
  4. Finally, the alert() function displays the value of t in an alert dialog.

Conclusion: #

Retrieving the text content of a <div> tag in JavaScript is accomplished by using the innerText property instead of value.

Remember that innerText is used for elements that contain visible text, while value is used for form elements like <input> or <textarea>.

By understanding the correct property to use, you can ensure that you retrieve the desired text content from a <div> tag without encountering the issue of getting undefined as the result.

save
listen
AI Answer
Write Your Answer
loading
back
View All