Follow us on X (Twitter)  Like us on Facebook  Connect with us on LinkedIn  Subscribe to our YouTube Channel  Subscribe to our WhatsApp Group

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.

 

jQuery to insert element at the middle of a post (www.kunal-chowdhury.com)

 

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:

    • The requirement is not to randomly insert at the middle of the page. This is because, it may insert the element at the middle of a line and/or within an existing element.
    • Requirement is to insert the content only when the paragraph (<p> tag) ends and/or have a line break (<br> or <br/>).

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.

 

Have a question? Or, a comment? Let's Discuss it below...

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.