Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a <p> tag dynamically

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'/>
like image 571
gkmohit Avatar asked Feb 28 '15 20:02

gkmohit


3 Answers

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' />
like image 90
dfsq Avatar answered Sep 18 '22 20:09

dfsq


You have a typo. It's getElementById, not getElementsById. Only one single element can be gotten with a certain ID.

And you should be using createElement and insertBefore to insert the element between the two other elements, appendChild appends to the element.

function addParagraphs() {

    var p2 = document.createElement('p');

    p2.innerHTML = "paragraph 2";

    var elem = document.getElementById("p1");

    elem.parentNode.insertBefore(p2, elem.nextSibling);

}
<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'/>
like image 20
adeneo Avatar answered Sep 21 '22 20:09

adeneo


A simple jQuery solution would be to use .insertAfter:

function addParagraphs() {
    var p2 = "<p>paragraph 2</p>";
    $(p2).insertAfter("#p1");
}

JSFiddle

like image 30
Harijoe Avatar answered Sep 18 '22 20:09

Harijoe