Create a <p> tag dynamically
dom, html, javascript
Solution
The simplest solution is to use the `insertAdjacentHTML` method which is very convenient for manipulations with HTML strings:
function addParagraphs() {
var p2 = "<p>paragraph 2</p>";
document.getElementById("p3").insertAdjacentHTML('beforebegin', p2);
}
<p id="p1">paragraph 1</p>
<p id="p3">paragraph 3</p>
<p id="p4">paragraph 4</p>
<input id="b2" type='button' onclick='addParagraphs()' value='Add P2' />
Another option is to use the `insertBefore` method, but it's a bit more verbose:
function addParagraphs() {
var p2 = document.createElement('p');
p2.innerHTML = 'paragraph 2';
var p3 = document.getElementById("p3");
p3.parentNode.insertBefore(p2, p3);
}
<p id="p1">paragraph 1</p>
<p id="p3">paragraph 3</p>
<p id="p4">paragraph 4</p>
<input id="b2" type='button' onclick='addParagraphs()' value='Add P2' />
Problem
How can I add a p tag in between id=p1 and id=p3 when I click the button "Add P2"? Here is the code I have so far. ``` function addParagraphs() { var p2 = "<p>paragraph 2</p>"; document.getElementsById("p1").appendChild(p2); } ``` ``` <p id ="p1" > paragraph 1</p> <p id ="p3" > paragraph 3</p> <p id ="p4" > paragraph 4</p> <input id="b2" type='button' onclick='addParagraphs()' value='Add P2'/> ```