Dynamically add new paragraph in html and js
Here are a few ways to dynamically add a new paragraph in HTML and JavaScript:
Method 1: Using innerHTML
HTML:
<div id="paragraph-container"></div>
JavaScript:
const paragraphContainer = document.getElementById('paragraph-container');
const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph!';
paragraphContainer.appendChild(newParagraph);
Method 2: Using insertAdjacentHTML
HTML:
<div id="paragraph-container"></div>
JavaScript:
const paragraphContainer = document.getElementById('paragraph-container');
paragraphContainer.insertAdjacentHTML('beforeend', '<p>This is a new paragraph!</p>');
Method 3: Using document.createElement and appendChild
HTML:
<div id="paragraph-container"></div>
JavaScript:
const paragraphContainer = document.getElementById('paragraph-container');
const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph!';
paragraphContainer.appendChild(newParagraph);
Method 4: Using a template literal
HTML:
<div id="paragraph-container"></div>
JavaScript:
const paragraphContainer = document.getElementById('paragraph-container');
paragraphContainer.innerHTML += `
<p>This is a new paragraph!</p>
`;
In all of these examples, we first get a reference to the element that will contain the new paragraph using document.getElementById
or a similar method. Then, we create a new paragraph element using document.createElement
or a similar method. We set the text content of the paragraph using textContent
or a similar method. Finally, we add the paragraph to the container element using appendChild
or a similar method.
Note that in the first three examples, we use appendChild
to add the paragraph to the container element. In the fourth example, we use the innerHTML
property to add the paragraph to the container element.