简体   繁体   中英

Insert html code after element

I have a html document which looks like this:

...html code...
<ul id="my_ul">
...html code...

Using javascript I want to insert the html code below inside the document, immediately after <ul id="my_ul"> :

<li><span>Some text</span><ul>

So far I have this, but not the expected results. Please, what am I doing wrong?

var para1 = document.createElement("li");
var para2 = document.createElement("span");
var node = document.createTextNode("Some text");
para2.appendChild(node);
var para3 = document.createElement("ul");
var element = document.getElementById("my_ul");
element.appendChild(para1);
element.appendChild(para2);
element.appendChild(para3);

Like this:

 var ul = document.getElementById("my_ul"); var li = document.createElement("li"); var span = document.createElement("span"); var text = document.createTextNode("Some text"); span.appendChild(text); li.appendChild(span); ul.appendChild(li); 
 <ul id="my_ul"> </ul> 

If you want shorter code without creating objects for each html elements just do this:

var element = document.getElementById("my_ul");
var html = '<li><span>Some text</span></li>'; 
element.innerHTML = html + element.innerHTML;

Is this what you want to do?

Demo: Fiddle

var para1 = document.createElement("li");
var para2 = document.createElement("span");
var node = document.createTextNode("Some text");
para2.appendChild(node);
para1.appendChild(para2);
element = document.getElementById("my_ul");
element.appendChild(para1);

Your code does this:

 element.appendChild(para1); 

Make the list item a child of the original list

 element.appendChild(para2); 

Make the span a child of the original list

 element.appendChild(para3); 

Make the new list a child of the original list


You need to append each element to the element you want to be its parent instead of appending everything to the original list.

Replace element with the appropriate variable.

 $(document).ready(function(){ var para1 = document.createElement("li"); var para2 = document.createElement("span"); var node = document.createTextNode("Some text"); para2.appendChild(node); var element = document.getElementById("my_ul"); element.appendChild(para1); para1.appendChild(para2); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <ul id="my_ul"> </ul> 

var ul = document.getElementById("my_ul");
var li = document.createElement("li");
var span = document.createElement("span");
var textNode = document.createTextNode("Some text");
span.appendChild(textNode);
li.appendChild(span);
ul.appendChild(li);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM