Home  >  Article  >  Web Front-end  >  How to use unordered list in javascript

How to use unordered list in javascript

PHPz
PHPzOriginal
2023-04-24 10:49:44976browse

Creating an unordered list using JavaScript is a very simple process. There are two main ways to achieve it.

The first method is to use the document.createElement() and document.createTextNode() methods. This approach creates a new li element, adds the text node to the li element, and then adds the li element to the ul element. The following is the code to implement this method:

var ul = document.createElement('ul'); // 创建无序列表
document.body.appendChild(ul); // 添加到HTML文档中

var fruits = ['apple', 'banana', 'orange', 'kiwi'];  // 定义水果数组

for (var i = 0; i < fruits.length; i++) {
  var li = document.createElement(&#39;li&#39;); // 创建列表项
  var text = document.createTextNode(fruits[i]); // 创建文本节点
  li.appendChild(text); // 将文本添加到列表项中
  ul.appendChild(li); // 将列表项添加到无序列表中
}

The second method is to use the innerHTML attribute. This approach creates an HTML string and then assigns it to the innerHTML attribute of the ul element, which will automatically parse the string into a DOM element. The following is the code to implement this method:

var fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;, &#39;kiwi&#39;];

var html = &#39;<ul>'; // 创建无序列表字符串

for (var i = 0; i < fruits.length; i++) {
  html += &#39;<li>' + fruits[i] + '</li>'; // 将列表项添加到无序列表字符串中
}

html += '</ul>'; // 关闭无序列表标签

document.body.innerHTML = html; // 将HTML字符串添加到HTML文档中

The above are two ways to create an unordered list using JavaScript. They are all very simple and only require some basic JavaScript knowledge to implement. So, whether you are a beginner or an experienced developer, these methods can power your project with unordered lists.

The above is the detailed content of How to use unordered list in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn