0

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>
4

2 回答 2

7

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.

于 2013-06-16T02:24:05.883 回答
1

I think the simplest way is like this,

var node = document.createElement("div");
var textnode = document.createTextNode('Content here...');
node.appendChild(textnode);
node.id = 'custom-div';
var referencenode = document.getElementById('main-content').children[1];
referencenode.parentNode.insertBefore(node, referencenode.nextSibling);

the code "referencenode.parentNode.insertBefore(node, referencenode.nextSibling);" will insert the node into after your selected element,

here's the DEMO

于 2016-11-25T04:22:17.803 回答