Forum Moderators: open
$("li:nth-child(3)").before("<li>foo </li>");
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="charset" value="utf-8">
<title>Insert Element with JavaScript</title>
<script>
function doInsertLI(insertPosition, insertValue) {
// At some point, you need to find a method of locating the
// <UL> element. I used the enclosing <DIV> with a known 'id' attribute.
// Usually, I'd just attach an 'id' directly on the <UL> element.
var boxEl = document.getElementById('myBox');
var ulEl = boxEl.getElementsByTagName('UL')[0];
var newLI = document.createElement('LI');
var newLIText = document.createTextNode(insertValue);
newLI.appendChild(newLIText);
ulEl.insertBefore(newLI, ulEl.childNodes[insertPosition+1]);
} // end doInsertLI
</script>
</head>
<body>
<h1 style="text-align:center;">Inserting An Element With JavaScript</h1>
<div id="myBox">
<ul>
<li>Block 1</li>
<li>Block 2</li>
<li>Block 3</li>
<li>Block 4</li>
</ul>
<br>
<p><a href="javascript:doInsertLI(3, 'This block gets inserted dynamically');">Insert <LI></a></p>
</div>
<br>
</body>
</html>