2

the code should add a new article element dynamically using js. Here is my code but it is not working.

js to create the article on the page once user clicks post button. `

document.getElementById("post-button").onclick = createPost();
var el = document.getElementById("post-button");
if (el.addEventListener)
    el.addEventListener("click", createPost(), false);
else if (el.attachEvent)
    el.attachEvent('onclick', createPost());


function createPost(){
    var article = document.createElement("article");
    article.setAttribute("id", "myarticle");
    article.className = "posts";

    var p = document.createElement("p");
    p = document.getElementByID("posting-area").value;




    // test case, append the content
    document.body.appendChild(article);
    document.getElementById("myarticle").appendChild(p);

}

`

html for user to enter post text.

<article class="posts">
               <img class="peopletofollowimg" src=Profile.jpg alt="View Profile Picture">
                <textarea id="posting-area" rows="6" cols="90" placeholder="Share Your Thoughts!">
                </textarea>
                    <button onclick="createPost()" id="post-button">Post!</button>


            </article>
Noha
  • 61
  • 1
  • 5
  • 1
    We can't help you unless you are more specific. what's not working? What errors are showing up in the JavaScript console? – Robbert Dec 24 '15 at 00:20

1 Answers1

0

I see a number of issues with your code. First, you are appending the p element to an element with id myarticle, but myarticle doesn't exist on your html snippet. You may have left that off.

Also, document.getElementByID("posting-area").value() is wrong. It should be getElementById("posting-area").value(). Remove the uppercase D in getElementByID.

And finally, you need to change the line

var p = document.createElement("p");
p = document.getElementById("posting-area").value;

to

var p = document.createElement("p");
p.innerHTML = document.getElementById("posting-area").value;

Here is a working jsfiddle

Robbert
  • 6,481
  • 5
  • 35
  • 61
  • it is working but whenever I click on post it adds the new div to the old one. @Robbert – Noha Dec 24 '15 at 12:45