DEV Community 👩‍💻👨‍💻

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

jQuery After And Before Example

In this article, We will see examples of the jquery after() and before() methods. The before() method inserts specified content before the selected elements.

The after() method inserts specified content after the selected elements.

Using the jquery after() method you can append HTML after div, append text to div, and jquery add text after span.

Using the before() method you can add HTML before div, append HTML before div, append text before div, and jquery add text after span.

Example: After() Method

In this example, we will append HTML after p tag. It appends some text to the element on the button click event.

Syntax:

$(selector).after(content);
Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").after("<p>Hello, Techsolutionstuff !!</p>");
  });
});
</script>
</head>
<body>

<h3>Jquery After And Before Example - Techsolutionstuff</h3>
<p>This is a paragraph tag.</p>

<button>Insert content after P tag</button>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Example: Before() Method

In this example, we will append HTML before p tag. It appends text to the element on the button click event.

Syntax:

$(selector).before(content);
Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").before("<p>Hello, Techsolutionstuff !!</p>");
  });
});
</script>
</head>
<body style="padding:20px;">

<h3>Jquery After And Before Example - Techsolutionstuff</h3>
<p>This is a paragraph tag.</p>

<button>Insert content before P tag</button>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await