How to add text to an existing div with jquery
Running example:
//If you want add the element before the actual content, use before()
$(function () {
$('#AddBefore').click(function () {
$('#Content').before('<p>Text before the button</p>');
});
});
//If you want add the element after the actual content, use after()
$(function () {
$('#AddAfter').click(function () {
$('#Content').after('<p>Text after the button</p>');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id="Content">
<button id="AddBefore">Add before</button>
<button id="AddAfter">Add after</button>
</div>
You need to define the button text and have valid HTML for the button. I would also suggest using .on
for the click handler of the button
$(function () {
$('#Add').on('click', function () {
$('<p>Text</p>').appendTo('#Content');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="Content">
<button id="Add">Add Text</button>
</div>
Also I would make sure the jquery is at the bottom of the page just before the closing </body>
tag. Doing so will make it so you do not have to have the whole thing wrapped in $(function
but I would still do that. Having your javascript load at the end of the page makes it so the rest of the page loads incase there is a slow down in your javascript somewhere.