Thuộc tính length của Storage trong HTML DOM dùng để lấy số lượng item hiện có trong storage object của trình duyệt. Storage object có thể là localStorage hoặc sessionStorage.
Cú pháp
Sử dụng localStorage:
localStorage.length;
Sử dụng sessionStorage:
sessionStorage.length;
Ví dụ
Ví dụ minh họa cho thuộc tính length:
<!DOCTYPE html> <html> <body>
<h1 style="text-align:center">Ví dụ thuộc tính length của Storage</h1>
<p>Lấy số item lưu trong localStorage bằng cách nhấn nút dưới đây</p>
<button onclick="itemNum()">LẤY SỐ LƯỢNG</button>
<p id="Sample"></p>
<script>
function itemNum() {
var num = localStorage.length;
document.getElementById("Sample").innerHTML = "Số lượng item storage là " + num;
}
</script> </body> </html>
Kết quả
Khi nhấn "LẤY SỐ LƯỢNG", hiển thị số item hiện có trong localStorage.