How do I attach a div to the corresponding li list

Hi guys,

I have a loop like this:

    <?php foreach($questions as $question) { ?>
        <li class=position_relative>
            <div class=floatleft>
                <?php echo $question['firsttolast']; ?>
            <a href="form.php" class=floatright>Answer</a>
    <?php } ?>

I want to attach a form to the corresponding li item if someone click on the link to answer the question with the code below:

var doc = document
  , ans = doc.getElementsByClassName('floatright');
for ( var i = 0, j = ans.length; i < j; i += 1 ) {
    (function(x) {
        ans[x].addEventListener('click', function(e) {
            var url = this.getAttribute("href");
            var xhr = newXMLHttpRequest();
  "GET", url, false);
            if (xhr.readyState == 4) {
                var div = doc.createElement('div');
                div.innerHTML = xhr.responseText;
                // HOW TO APPEND IT TO THE <LI>?

How do I do it?
I want it be like a thread comment like in facebok (no real time need).
The current practice I use is going to the form page and return when submit.
I want to add ajax to this case.

thank you,

Hi, Nico :smiley:

Can you use jQuery in your project? If so, I can write an example how to achieve this with jQuery for you.


I don’t use jQuery. People say it was bad and use vanilla JavaScript instead, So I don’t use it ever since I heard of vanilla JavaScript long time ago.

People are wrong. It helps to save huge amount of time and makes you code shorter and cleaner. But, that’s your choice.

Okay Space Captain :blush:
You can show me jQuery code. I’ll use it.


Here is it:
And here is form html:

Thank you,

Wow! That’s great. I’ve never seen something like this with jQuery.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.