How to insert an element at the middle of a post using jQuery?
There could be some possible business cases where we need to insert a HTML element inside a post. This should not be a static one but a dyna...- Article authored by Kunal Chowdhury on .
There could be some possible business cases where we need to insert a HTML element inside a post. This should not be a static one but a dyna...- Article authored by Kunal Chowdhury on .
There could be some possible business cases where we need to insert a HTML element inside a post. This should not be a static one but a dynamically injected at the middle of the article. So, what to do in such case? How can we insert it by writing some code?
Today in this blog post, we are going to see the same with the help of jQuery code. This will not only reduce the burden of writing huge code, but also give a better performance.
If you are building a webpage and have any business need to dynamically insert a HTML content or ads block, you can use jQuery script to perform the same easily without any hassle. Before implementation of the code, you first need to understand the case of the logic as mentioned below:
For this, we need to find out all the tags having 'p' and/or 'br'. Then we have to get the content length of the same and find out the mid of the content where 'p' and/or 'br' exists. And then after the end tag of the said element, insert the content/element that you want to dynamically place.
Here's the code for your reference:
<script>
$(document).ready(function() {
var content = $('.content').find('p, br'); // '.content' is the class of the panel
var midLength = parseInt(content.length/2);
content.eq(midLength).after("<p>Your content here</p>");
});
</script>
If you came to this page searching on this topic, I hope, this solved your problem. Drop a line below with your comments. If you have any other approach to share with the other developers, also post your solution in the comments section.
Solution Architect & Former Microsoft MVP
Kunal Chowdhury is an enterprise solution architect and former multi-year Microsoft MVP. He is the author of three technical books: Windows Presentation Foundation Development Cookbook, Mastering Visual Studio 2017, and the Mastering Visual Studio 2019.
He publishes technical and non-technical articles on Kunal-Chowdhury.com.