Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to access cookies using document object in JavaScript?
In JavaScript, you can access and read cookies using the document.cookie property. This property returns a string containing all cookies stored in the browser for the current domain.
The document.cookie string contains a list of name=value pairs separated by semicolons, where each name represents a cookie name and its corresponding value is the cookie's string value.
In this article, we will learn how to access cookies using the document object in JavaScript.
Syntax
document.cookie
Return Value: A string containing all cookies for the current domain, formatted as semicolon-separated name=value pairs.
Reading All Cookies
The simplest way to access cookies is to read the entire cookie string:
<html>
<head>
<script>
// First set some cookies
document.cookie = "username=john";
document.cookie = "theme=dark";
document.cookie = "language=en";
// Read all cookies
function showAllCookies() {
var allCookies = document.cookie;
document.getElementById("output").innerHTML = "All Cookies: " + allCookies;
}
</script>
</head>
<body>
<button onclick="showAllCookies()">Show All Cookies</button>
<div id="output"></div>
</body>
</html>
Extracting Specific Cookies
To extract a specific cookie by name, follow these steps:
- Get the complete cookie string using
document.cookie - Split the string at semicolons (";") to get individual cookies
- Parse each cookie to separate name and value
- Store in a Map or object for easy retrieval
<html>
<head>
<script>
function getCookieByName(name) {
// Set some test cookies
document.cookie = "firstname=Alice";
document.cookie = "lastname=Smith";
document.cookie = "age=25";
// Get all cookies
let allCookies = document.cookie;
// Split into individual cookies
let cookieArray = allCookies.split(';');
// Create a Map to store cookies
let cookieMap = new Map();
// Parse each cookie
for(let cookie of cookieArray) {
let parts = cookie.trim().split('=');
if(parts.length === 2) {
cookieMap.set(parts[0], parts[1]);
}
}
// Return the requested cookie
return cookieMap.get(name) || "Cookie not found";
}
function displayCookie() {
let firstName = getCookieByName("firstname");
let lastName = getCookieByName("lastname");
let age = getCookieByName("age");
document.getElementById("result").innerHTML =
"First Name: " + firstName + "<br>" +
"Last Name: " + lastName + "<br>" +
"Age: " + age;
}
</script>
</head>
<body>
<button onclick="displayCookie()">Get Specific Cookies</button>
<div id="result"></div>
</body>
</html>
Complete Cookie Management Example
Here's a comprehensive example that demonstrates setting and reading cookies:
<html>
<head>
<script>
// Function to set a cookie
function setCookie(name, value, days) {
let expires = "";
if (days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
// Function to get a specific cookie
function getCookie(name) {
let nameEQ = name + "=";
let cookies = document.cookie.split(';');
for(let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length);
}
}
return null;
}
function manageCookies() {
// Set cookies
setCookie("user", "JohnDoe", 7);
setCookie("preference", "darkmode", 30);
// Read cookies
let user = getCookie("user");
let preference = getCookie("preference");
document.getElementById("demo").innerHTML =
"User: " + (user || "Not set") + "<br>" +
"Preference: " + (preference || "Not set") + "<br>" +
"All cookies: " + document.cookie;
}
</script>
</head>
<body>
<h2>Cookie Management Demo</h2>
<button onclick="manageCookies()">Set and Read Cookies</button>
<div id="demo"></div>
</body>
</html>
Key Points
-
document.cookiereturns all cookies as a single semicolon-separated string - Cookie values may contain spaces, so use
trim()when parsing - Always check if a cookie exists before using its value
- Cookies are domain-specific and only accessible to the domain that set them
Browser Compatibility
The document.cookie property is supported in all major browsers and is part of the standard DOM API.
Conclusion
JavaScript's document.cookie property provides a simple way to access browser cookies. By parsing the returned string, you can extract specific cookie values for use in your web applications.
