NokX
1
i’m wanting to add a new <li> to an existing <ul>, but i want it to appear at the top of the list - not append to the bottom.
i’m assuming there’s a semi easy way to do this?
var ul = document.getElementById('my-list');
var li = document.createElement('li');
ul.appendChild(li);
that’s currently how appending works, i just want to add it at the top.
use insertBefore ie
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" media="screen" />
<style type="text/css"></style>
<script type="text/javascript">
function add(what, where) {
var d = document.getElementById('test');
var li = document.createElement('LI');
li.appendChild(document.createTextNode(what));
d.insertBefore(li, d.childNodes[where]);
}
</script>
</head>
<body>
<ul id="test">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
<br /><a href="javascript:add('10',0);">Add 10 at 0</a>
</body>
</html>