Add New List Item

  • Thread starter christopher.secord
  • Start date
C

christopher.secord

In the code below, I have an ordered list and a javascript function to
add new list items to the list. My problem is that the function adds
items to the bottom of the list. How can I go about adding items to
the top of (or anywhere else in the list)?

thanks
chris

<script type="text/javascript">
function addLI(id){
var Parent = document.getElementById(id);
var NewLI = document.createElement("LI");

NewLI.innerHTML = "this is a test";

Parent.appendChild(NewLI);
}
</script>
</head>

<body>
<input type="button" onclick="return addLI('test');" value="add LI">

<ol id="test">
<li>1</li>
<li>2</li>
</ol>
 
R

RobG

In the code below, I have an ordered list and a javascript function to
add new list items to the list. My problem is that the function adds
items to the bottom of the list. How can I go about adding items to
the top of (or anywhere else in the list)?

thanks
chris

<script type="text/javascript">
function addLI(id){
var Parent = document.getElementById(id);
var NewLI = document.createElement("LI");

Variable names starting with a capital letter are normally reserved for
constructors - it's just a convention, but worth following.

NewLI.innerHTML = "this is a test";

It's not a good idea to mix W3C DOM with proprietary (though widely
supported) methods when it isn't necessary:

NewLI.appendChild(document.createTextNode("this is a test"));

Parent.appendChild(NewLI);

Parent.insertBefore(NewLI, Parent.firstChild);
 
C

christopher.secord

RobG said:
It's not a good idea to mix W3C DOM with proprietary (though widely
supported) methods when it isn't necessary:

thanks rob, I didn't know that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,115
Latest member
JoshuaMoul
Top