ใช้ trim(), split(',') แยกข้อความ แล้วสร้าง <ul><li> ใหม่
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="commaSeparated"> This,is,the,first,JavaScript,program </div>
<script>
var allTheData = document.querySelector('.commaSeparated').textContent.trim().split(',');
var separateList = '';
allTheData.forEach(function(value) {
separateList += '- ' + value + '
';
});
separateList += '
';
document.querySelector(".commaSeparated").innerHTML = separateList;
</script>
</body>
</html>
วิธีรันโปรแกรม
- บันทึกไฟล์ชื่อ "anyName.html" หรือ "index.html"
- คลิกขวาที่ไฟล์ เลือก "Open with Live Server" ใน VS Code Editor
ผลลัพธ์
Div เดิมจะกลายเป็น Unordered List แต่ละ Item อยู่บรรทัดแยกกัน