Check if Paragraph Exists Then Insert Element Using JavaScript

Here is an HTML script example to check if paragraph exists then insert an element using JavaScript.

Insert an Element If a Paragraph Exists Using JavaScript

In the following example, it will check that if the third paragraph exists then it will insert another paragraph using JavaScript.

<!DOCTYPE html>

window.onload=function() {

var div = document.getElementById("target");

var paras = div.getElementsByTagName("p");

var newPara = document.createElement("p");
if (paras[3]) { 
div.insertBefore(newPara, paras[3]);
} else {

newPara.innerHTML="This is the new paragraph inserted after 3rd paragraph";

<div id="target">
<p>This is the first paragraph</p>
<p>This is the second paragraph</p>
<p>This is the third paragraph</p>
<p>This is the fourth paragraph</p>


This is the first paragraph

This is the second paragraph

This is the third paragraph

This is the new paragraph inserted after 3rd paragraph

This is the fourth paragraph

Leave a Comment