How To Add Text In P Tag Using Javascript
In this article, you are going to learn 5 ways to add text in <p> tag using javascript.
Add text in p tag using innerHTML property #
To add text within a <p> tag using JavaScript, you can use the innerHTML property of the paragraph element.
- Get the reference to the paragraph element using its ID. In this example, the ID is myParagraph.
- Assign the desired text to the innerHTML property of the paragraph element.
- The innerHTML property allows you to add HTML content as well, not just plain text.
Adding text in paragraph using textContent property #
Another way to add text to a <p> tag is by utilizing the textContent property.
The textContent property treats the assigned value as plain text, not as HTML content.
If the assigned text includes special characters, they will be displayed as they are without being interpreted as HTML.
Adding text in paragraph using createTextNode() method #
An alternative approach to add text within a <p> tag is by creating a text node using the createTextNode() method.
Create a new text node using the createTextNode() method and assign the desired text as its content.
Use the appendChild() method of the paragraph element to append the created text node as a child. The text assigned will be added to the end of any existing content within the <p> tag.
Insert content inside p tag using insertAdjacentHTML() method #
The insertAdjacentHTML() method provides a flexible way to add text or HTML content in various positions relative to an element.
Call the insertAdjacentHTML() method on the paragraph element. Pass the desired position as the first argument. In this case, beforeend is used to add the text as the last child of the paragraph element.
The second argument of insertAdjacentHTML() is the text or HTML content to be inserted. Here, it's "This is the added text". The content will be inserted at the specified position within the <p> tag, without affecting existing content or other elements inside it.
<button onclick="toggleText()">Toggle Text</button>
<p id="textToToggle">This is the text to be toggled.</p>
<script>
function toggleText() {
var textElement = document.getElementById("textToToggle");
textElement.style.display = (textElement.style.display === "none") ? "block" : "none";
}
</script>
[1] The CSS initially sets the <p> tag to display: none.
[2] The JavaScript function toggleText() toggles the display property between block and none.