How to get the cookies associated with a document in JavaScript?


In this article we are going to learn how to get the cookies associated with a document in JavaScript.

The cookies property present in the Document interface is used to return the cookies associated with a Document in JavaScript. The Cookies are small strings of data that is present in the form of name=value pairs inside a browser. Each cookie is delimited by a ‘;’.

Cookies are used for client-server applications. Cookies have an expiration date. They have a size limit of 4KB.

To get a better understanding of this concept, let’s look into the examples further in this article.

Syntax

The syntax to get the cookies associated with in a document is shown below.

document.cookie;

Example 1

The following is the example program where we displayed the cookies present inside a document.

<html>
<body>
   <p id="cookie"></p>
   <script>
      document.getElementById("cookie").innerHTML = "Cookies associated with this document: " + document.cookie;
   </script>
</body>
</html>

On executing the above code, the following output is generated.

Example 2

The below program is an example to display the cookies present inside a document.

<!DOCTYPE html>
<html>
<head>
   <title>To display the domain of the server that loaded a document in JavaScript</title>
</head>
   <body style="text-align : center">
      <h3>To display the domain of the server that loaded a document in JavaScript</h3>
      <p id='cookies'></p>
      <script>
         document.getElementById('cookies').innerHTML = 'The cookies associated in this document are : '+document.cookie ;
      </script>
   </body>
</html>

On executing the above code, the following output is generated.

Example 3

The below is an example program to create user-defined cookies. i.e. to set and get the cookies and finally to display the cookies.

<!DOCTYPE html>
<html>
<head>
   <title>To display the domain of the server that loaded a document in JavaScript</title>
</head>
<body style="text-align : center">
   <h3>To display the domain of the server that loaded a document in JavaScript</h3>
   <p id='cookies'></p>
   <script>
      document.cookie = "username= John Nicholas; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/"; // Set the cookie
      let x = document.cookie; // Get the cookie
      document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; // Delete the cookie by not specifying any value and set the expires value to past date.
      document.getElementById('cookies').innerHTML = 'The cookies associated in this document are : '+document.cookie ;
   </script>
</body>
</html>

On executing the above code, the following output is generated.

Updated on: 08-Dec-2022

524 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements