Tutorials using JS
Problem Statement
given a paragraph element, change the text content of the paragraph element using JavaScript
Solution
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';
Program
when user clicks on the button, we get the paragraph with the id message
, and set its text using innerText
property
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<button id="myBtn">Click me</button>
<p id="message">This is a paragraph.</p>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
const myPara = document.getElementById("message");
//set the text in paragraph element
myPara.innerText = "This is a coded message.";
});
</script>
</body>
</html>