Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Chuyển text phân cách dấu phẩy trong div thành danh sách (list) với JavaScript

Lấy textContent của div, trim(), split(',') thành mảng, duyệt tạo thẻ <li> bọc trong <ul>.

Ví dụ


<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSV thành List</title>
</head>
<body>
    <div class="commaSeparated">This,is,the,first,JavaScript,program</div>

    <script>
        const div = document.querySelector('.commaSeparated');
        const items = div.textContent.trim().split(',');
        
        let html = '
    '; items.forEach(item => html += `
  • ${item}
  • `); html += '
'; div.innerHTML = html; </script> </body> </html>

Cách chạy

Lưu index.html, mở Live Server.

Kết quả

Div hiển thị danh sách gạch đầu dòng:

  • This
  • is
  • the
  • first
  • JavaScript
  • program

Cải tiến: item.trim() để xóa space thừa, filter(Boolean) bỏ item rỗng.