How to add html after or before an element using jQuery

In jQuery, we can use the after() and before() methods to insert content (text or html tags) outside of the selected elements. With using before method we can inserts content before (outside) the selected tags and with using after method we can inserts content after (outside) the selected tags. Below are example of after() and before() methods: before() & after() methods example


<html>
<head>
    <title>Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

    <div id="sourceElem">
        

Source Content

</div> <br> <button id="btnBeforeText">Before example</button> <button id="btnAfterText">After example</button> <script> $(document).ready(function () { $('#btnBeforeText').on('click', function () { $("#sourceElem").before("

Before paragraph example.

"); }); $('#btnAfterText').on('click', function () { $("#sourceElem").after("

After paragraph example.

"); }); }); </script> </body> </html>