netizen0911 netizen0911 - 1 month ago 4
HTML Question

Javascript: How to add "div" element right after 2nd generic "p" tag (w/o ID nor Class) inside of every post or content section?

How do I go about inserting a custom "div" element that appears right after 2nd generic (w/o adding ID or Class) "p" node/tag in the content section of every pages I want it to be in, by using JavaScript?

For example:

<div id="main-content">
<p>1st paragraph content.....</p>
<p>2nd paragraph content.....</p>
<p>3rd paragraph content.....</p>
</div>


The output:

<div id="main-content">
<p>1st paragraph content.....</p>
<p>2nd paragraph content.....</p>
<div id="custom-div">Content here...</div>
<p>3rd paragraph content.....</p>
</div>

Answer

Given your html:

<input type='button' onclick='addText();' value='Add To List'/>
<input type='text' id='input'/>
<div id="main-content">
  <p>1st paragraph content.....</p>
  <p>2nd paragraph content.....</p>
  <p>3rd paragraph content.....</p>
</div>

And since you didn't mention jQuery I will provide an answer with plain Javascript:

var appender=1;
    function addText(){
        var parentDiv = document.getElementById('main-content');
        var input = document.getElementById('input').value;    
        var node = document.createElement("DIV");
        var textnode = document.createTextNode(input);
        node.appendChild(textnode);     
        node.id = 'custom-div_' + appender;
        var child = parentDiv.children[2];
        parentDiv.insertBefore(node, child);
        appender++;

    }

Here is a working demo

Note that there is a global var so you can assign different ID's to your dynamically created elements.

Edit

As per user request, the following code will add that content on load :

<body onload="addText()">
<div id="main-content">
  <p>1st paragraph content.....</p>
  <p>2nd paragraph content.....</p>
  <p>3rd paragraph content.....</p>
</div>
</body>

Here is the updated Javascript:

var appender=1;
function addText(){
    var parentDiv = document.getElementById('main-content');      
    var node = document.createElement("DIV");
    var textnode = document.createTextNode("This was added dinamically");
    node.appendChild(textnode);     
    node.id = 'custom-div_' + appender;
    var child = parentDiv.children[2];
    parentDiv.insertBefore(node, child);
    appender++;

}

Here is the new demo

Note that the variable appender is not longer needed I'm leaving in case you want to merge functionality.