Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create ul and li elements in javascript.

Tags:

javascript

I am trying to create ul and li element in my codes by using javascript. I have following:

var test=document.createElement('section'); test.setAttribute('id','test');  var ul=document.createElement('ul');   document.body.appendChild(test); test.appendChild(ul);  for (var i=0; i<array.length; i++){      var li=document.createElement('li');      ul.appendChild(li);     li.innerHTML=li.innerHTML + array[i];  } 

My array is parsed using json_encode from php

array[0]='aaa'; array[1]='bbb'; array[2]='ccc'; 

CSS

section {       display: block;     width: 200px;     margin: 50px auto;     border: 3px solid red;  } 

Everything works fine except the list style dot is outside of my section tag.

It displays like this in Chrome and IE but firefox work fine.

 ------------- *| aaa       | *| bbb       | *| ccc       |  ------------- 

I want my dot inside my section tag. Anyone idea? Thanks a lot.

like image 216
Rouge Avatar asked Jul 05 '12 19:07

Rouge


People also ask

What is UL in JavaScript?

<ul>: The Unordered List element. The <ul> HTML element represents an unordered list of items, typically rendered as a bulleted list.

How do I add Li to UL?

To add new li to ul on click with JavaScript, we can call the appendChild method. const ul = document. getElementById("list"); const li = document. createElement("li"); li.


1 Answers

Here is my working code :

<!DOCTYPE html> <html> <head> <style>    ul#proList{list-style-position: inside}    li.item{list-style:none; padding:5px;} </style> </head> <body>     <div id="renderList"></div> </body> <script>     (function(){         var ul = document.createElement('ul');         ul.setAttribute('id','proList');          productList = ['Electronics Watch','House wear Items','Kids wear','Women Fashion'];          document.getElementById('renderList').appendChild(ul);         productList.forEach(renderProductList);          function renderProductList(element, index, arr) {             var li = document.createElement('li');             li.setAttribute('class','item');              ul.appendChild(li);              li.innerHTML=li.innerHTML + element;         }     })(); </script> </html> 

working jsfiddle example here

like image 60
Sunny S.M Avatar answered Sep 21 '22 15:09

Sunny S.M