How Can I Use After and Before Methods With JQuery

admin_img Posted By Bajarangi soft , Posted On 13-10-2020

In jQuery after() method inserts content AFTER the selected HTML elements and jQuery before() method inserts content BEFORE the selected HTML elements.So today we discuss how to use after and before methods

How Can I Use After and Before Methods With JQuery

Step 1:Create index.html file and implement below code.

<img src="../image/demo1.jpg" alt="jQuery" width="200" height="140"><br><br>

<button  class="btn btn-success" id="btn1">Insert before</button>
<button  class="btn btn-success" id="btn2">Insert after</button>


Step 2:Implement jquery to use after and before method.

<script>
    $(document).ready(function(){
        $("#btn1").click(function(){
            $("img").before("<b>Before</b>");
        });

        $("#btn2").click(function(){
            $("img").after("<i>After</i>");
        });
    });
</script>


Complete Code For After and Before Methods With JQuery
<!DOCTYPE html>
<html>
<head>
    <title>How Can I Use After and Before Methods With JQuery</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<style>
    body {
        background: darkolivegreen;
    }

</style>
<body>
<div class="container">
    <br><br><br>
    <div class="text-center">
        <h2 id="color" style="color: White">After and Before Methods With JQuery</h2>
    </div>
    <br>
    <br>

    <div class="well">
        <img src="../image/demo1.jpg" alt="jQuery" width="200" height="140"><br><br>

        <button  class="btn btn-success" id="btn1">Insert before</button>
        <button  class="btn btn-success" id="btn2">Insert after</button>
    </div>

</div>
</body>
</html>
<script>
    $(document).ready(function(){
        $("#btn1").click(function(){
            $("img").before("<b>Before</b>");
        });

        $("#btn2").click(function(){
            $("img").after("<i>After</i>");
        });
    });
</script>


 

Related Post