Search code examples
javascriptjqueryajaxdhtml

appending <form> above the previous <form> or multiple <form> tags using javascript/jquery


I am working on a webpage which has a comment box using which a person can comment, these comments are displayed on the same page dynamically using AJAX. For example, when you submit a comment it gets posted on top of the previous comments.

Here is what i'm doing in AJAX:

xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

            var newDivElement = document.createElement('form');
            newDivElement.setAttribute('id',"postForm");
            newDivElement.setAttribute('action',"updateRecords.php");
            newDivElement.setAttribute('method',"post");
            newDivElement.innerHTML=postContent; 

            document.getElementById('mainPostContainer').appendChild(newDivElement);
        }
    }

(postcontent consists of a div which contains the comment)

Now, if I post two consecutive comments, say "this is 1st comment" and "this is 2nd comment", they get posted in the following order:

<div id=mainPostContainer>
    <form id="postForm" action="updateRecords.php" method="post"><div id="post"> this is 1st comment </div></form>
    <form id="postForm" action="updateRecords.php" method="post"><div id="post"> this is 2nd comment </div></form>
</div>

But I want them in the following order:

<div id=mainPostContainer>
    <form id="postForm" action="updateRecords.php" method="post"><div id="post"> this is 2nd comment </div></form>
    <form id="postForm" action="updateRecords.php" method="post"><div id="post"> this is 1st comment </div></form>
</div>

I tried using insertBefore() instead of append, but I dont know how to get the previous element (ie. the last created <form>).

Am I doing something wrong here? Or is there a better way to do what I am trying to do? Maybe using jQuery?

EDIT: I am using <form> because there are input elements of type button and text inside the form, I didnt mention them just to keep it simple.


Solution

  • Adding New Element as the First Child

    Plain Old JavaScript

    HTML:

    <div id="mainPostContainer"><p>1</p></div>
    

    JavaScript:

    var myContainer = document.getElementById("mainPostContainer");
    var p = document.createElement("p");
    p.innerHTML = "2";
    myContainer.insertBefore(p,myContainer.firstChild);
    

    Example:

    jsfiddle


    jQuery

    HTML:

    <div id="mainPostContainer"><p>1</p></div>
    

    JavaScript:

    var p = $("<p>2</p>");
    $("#mainPostContainer").prepend(p);
    

    Example:

    jsfiddle