Javascript Create Ul Li From Array With Code Examples In this article, we will see how to solve Javascript Create Ul Li From Array with examples. There are a variety of approaches that can be taken to solve the same problem Javascript Create Ul Li From Array. The remaining solutions are discussed further down. Using many examples,
we’ve learned how to tackle the Javascript Create Ul Li From Array problem. HTML <ul> and <li> elements are often used to show a list of items with bullet points on a web page. You can add these elements at design time and dynamically at run time. I’ll show you how you can create <ul> and <li> elements dynamically using JavaScript. Create HTML ul and li elements using XML data in jQuery Let’s see an example. The Markup and Script In the markup section, I have a <div> element, which will serve as a container and here I’ll append the dynamically created list items to it. <!DOCTYPE html> <html> <body> <div id='container'></div> </body> <script> var arr = ['alpha', 'bravo', 'charlie', 'delta', 'echo']; var cont = document.getElementById('container'); var ul = document.createElement('ul'); ul.setAttribute('style', 'padding: 0; margin: 0;'); ul.setAttribute('id', 'theList'); for (i = 0; i <= arr.length - 1; i++) { var li = document.createElement('li'); li.innerHTML = arr[i]; li.setAttribute('style', 'display: block;'); ul.appendChild(li); } cont.appendChild(ul); </script> </html> Try it Using ES6 FeaturesIf you are using ES6, the script should be, <script> const arr = ['alpha', 'bravo', 'charlie', 'delta', 'echo']; const cont = document.getElementById('container'); const ul = document.createElement('ul'); ul.setAttribute ('style', 'padding: 0; margin: 0;'); ul.setAttribute('id', 'theList'); for (i = 0; i <= arr.length - 1; i++) { const li = document.createElement('li'); li.innerHTML = arr[i]; li.setAttribute ('style', 'display: block;'); ul.appendChild(li); } cont.appendChild(ul); </script> You can also do this using jQuery. I personally prefer the JavaScript and I have explained it in the above example. Using the createElement() method, you can easily create any DOM element dynamically. Well, that’s it. Thanks for reading. ☺ ← PreviousNext → JAVASCRIPT 자바스크립트 ( div,ul,li 등 )엘리먼트 추가하기 - createElement , appendChild 예제자바스크립트 ( div,ul,li 등 )엘리먼트 추가하기 - createElement , appendChild 예제 실행결과 : [ jsfiddle ] <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> </head> <body> <div id='a'> <script type='text/javascript'> </body> </html> 사용된 속성 - ( 속성명 클릭시 상세 설명 확인 가능 ) |