Yasir
Yasir

Reputation: 3907

how to add paragraph on top of div content

How can I add multiple paragraph tag, newly tag on top within div container.

<div id="pcontainer">
  <p>recently added on top every time on click event recently added paragarph on top</p>
  <p>added before recent</p>
</div>

I am using append but every time I click button it add to bottom I need it to added on top of all paragraph please help.

Upvotes: 33

Views: 76248

Answers (8)

ego-lay atman-bay
ego-lay atman-bay

Reputation: 99

A more updated solution without jquery is to use the prepend() method.

function add() {
  let p = document.createElement('p')
  p.innerText = 'added before'
  document.getElementById('pcontainer').prepend(p)
}

button = document.getElementById('add')
button.addEventListener('click', add)
<button id="add">add</button>

<div id="pcontainer">
  <p>begin</p>
</div>

Upvotes: 0

Palak Goyal
Palak Goyal

Reputation: 11

You can use a little trick. For example, first store your new html in a variable and append it in the container with the old content.

const container = document.getElementById("pcontainer")
container.innerHTML = `<p>new para you want to add</p> ${container.innerHTML}` 

Upvotes: 1

Mattijs
Mattijs

Reputation: 1930

A more elegant way without jQuery:

var container = document.getElementById('pcontainer');
container.insertBefore(document.createElement("p"), container.firstChild);

This assumes there is already an element in the container btw.

Upvotes: 51

Defender
Defender

Reputation: 31

Here is a way without jQuery:

function prependParagraphs()
{
     var choosenDiv = document.getElementById("pcontainer");
     for(var i=0; i<5; i++)
     {
         var newP = document.createElement("p");
         var text = document.createTextNode("new paragraph number: " + i);
         newP.appendChild(text);
         choosenDiv.insertBefore(newP, choosenDiv.firstChild);
     }
}

Upvotes: 3

karl
karl

Reputation:

An example for non jQuery-users:

document.getElementById('pcontainer').innerHTML = '<p>new paragraph</p>' + document.getElementById('pcontainer').innerHTML;

maybe not as short and nice though :)

Upvotes: 18

moff
moff

Reputation: 6503

You may use prepend to add the paragraph at the top of the container:

// HTML: <div><p>Lorem ipsum</p></div>
$('div').prepend('<p>Bla bla bla');

Update: Regarding your comment about how to fade in the paragraph - use fadeIn:

$("#pcontainer").prepend($('<p>This paragraph was added by jQuery.</p>').fadeIn('slow'));

A working demo: http://jsbin.com/uneso

Upvotes: 57

Brandon Montgomery
Brandon Montgomery

Reputation: 6986

Specific to your HTML, it would be:

$("#pcontainer").prepend('<p>here's a new paragraph!</p>');

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532435

Try using prepend instead of append.

Upvotes: 3

Related Questions