JavaScript Code

How to change text of paragraph using JavaScript?

Tutorials using JS

Problem Statement

given a paragraph element, change the text content of the paragraph element using JavaScript


to set or change the text of a paragraph element using JavaScript, we can use Element.innerText property. get the paragraph element and set its innerText property with the required text

paragraphElement.innerText = 'hello world';


when user clicks on the button, we get the paragraph with the id message, and set its text using innerText property

<!DOCTYPE html>
<h1>JavaScript Tutorial</h1>
<button id="myBtn">Click me</button>
<p id="message">This is a paragraph.</p>

document.getElementById("myBtn").addEventListener("click", function() {
  const myPara = document.getElementById("message");
  //set the text in paragraph element
  myPara.innerText = "This is a coded message.";


Copyright @2022