OrangePineapple OrangePineapple - 1 month ago 5
Javascript Question

adding both button and div together

I'm new to

JavaScript
so please be patient with me.

I'm currently fiddling with this code:

$("input[type = submit]").click(function(){
$("<div>").attr("class","apples").html(itemInput.value).appendTo(".div1");
$("<button>").appendTo(".apples");

clearInput();
})


basically it adds a button along with a div when you click submit. But its adding more buttons than div. For example. Pressing submit once gives me 1 div, and 1 button (which is what I want), pressing submit the 2nd time, gives 1 div and 2 buttons. pressing submit the 3rd time, gives me 1 div and 3 buttons. The more I press submit the more buttons will spawn with a single div.

I was wondering how I can just make it 1 div with 1 button attached to it once created.

Edit:
HTML: This is basically the whole thing. excluding
<head>
.

<body>
<div class = "centerAlign" >
<div class = "div1">
<input id="itemInput" type="text" placeholder="add to-do items " />
<input type="submit" value="ADD"/>
</div>
</div>

<script>
$("input[type = submit]").click(function(){
$("<div>").attr("class","apples").html(itemInput.value).appendTo(".div1");

$("<button>").appendTo(".apples");

}
clearInput();
})
function clearInput(){
itemInput.value = "";
}
</script>
</body>
</html>

Answer

If you want appear button to last created div with class apples this could be the way:

$("input[type = submit]").click(function(){
    $("<div>").attr("class","apples").html(itemInput.value).appendTo(".div1");
    $("<button>").appendTo($(".apples").last());

        clearInput();
    }); 

With the last() function you get the last element from DOM.

Here I created Fiddle i hope it help https://jsfiddle.net/Lyt3otrp/

Wish you luck ;]