Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dom
textcontent
communitycreator

What is DOM property "textContent"?

Ayush Trivedi

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The textContent is the DOM property that is used to set text content for the HTML element or get the text content written inside that element.

If you set the text using textContent for an element, then the other child elements will be removed and only this text will be added in that element. This means that it will override the element content.

Code

Let’s use textContent on an element to get its text.

Console

Code explanation

  • In line # 5: We have a <P> element with id elem. Inside this paragraph tag, we write some text.

  • In line # 7: We have written a button tag having a function change(). This function will be called when the user clicks the button.

  • In line # 8: Added another button with setText function, to set the text content in the p element.

  • From lines # 10-14: We have written the JavaScript code in the script tag. We have defined the function change() which will be called when the user clicks the button from the HTML page.

  • In line # 12: In function change(), we will get the <p> element using document.getElementById() and passing the id elem.

  • In line # 13: We will apply the property textContent on the element object and store its output in a variable.

  • In line # 13: Print the value returned by the property textContent using console.log().

  • In line # 16: The setText() function to set new text content in the element.

  • In line # 17: We will get the <p> element using document.getElementById() and passing the id elem.

  • In line # 18: Applying textContent on the p element and assigning new text content to it.

Output

When we click the GET Text button the console prints the exact text value which is in the <p> paragraph tag. And when SET button is clicked new text is added to it.

RELATED TAGS

dom
textcontent
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring