javascripthtmldynamicposting

I am creating a social media sort of website, and I need to let the user dynamically post


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>

Solution

  • 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