Javascript Element How to - Create new LI element and append to UL








Question

We would like to know how to create new LI element and append to UL.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!-- w  ww .  j ava2 s.c  o  m-->
    el = document.createElement('li');
    el.innerHTML = 'Jeff';
    document.getElementById('MyUl').appendChild(el);
}
</script>
</head>
<body>
  <ul id="MyUl">
    <li>Dave</li>
  </ul>
</body>
</html>

The code above is rendered as follows: