How to access cookies using document object in JavaScript?

JavascriptWeb DevelopmentFront End Technology

With JavaScript, you can easily access/ read cookies with the “document.cookie” property. Reading a cookie is just as simple as writing one because of the value of the document.cookie object is the cookie.

The document.cookie string will keep a list of name=value pairs separated by semicolons, where the name is the name of a cookie and value is its string value.

Example

You can try to run the following code to learn how to access cookies using document object in JavaScript

Live Demo

<html>
   <head>
      <script>
         <!--
            function ReadCookie() {
               var allcookies = document.cookie;
               document.write ("All Cookies : " + allcookies );

               // Get all the cookies pairs in an array
               cookiearray = allcookies.split(';');

               // Now take key value pair out of this array
               for(var i=0; i<cookiearray.length; i++) {
                  name = cookiearray[i].split('=')[0];
                  value = cookiearray[i].split('=')[1];
                  document.write ("Key is : " + name + " and Value is : " + value);
               }
            }
         //-->
      </script>
   </head>
   <body>
      <form name="myform" action="">
         <p> click the following button and see the result:</p>
         <input type="button" value="Get Cookie" onclick="ReadCookie()"/>
      </form>
   </body>
</html>
raja
Published on 31-Jan-2018 08:27:07
Advertisements