The HTML DOM cookie property is used for creating, reading and deleting cookies.The cookies are used by website to keep track of user specific information . This method has return type of string containing semi-colon separated list of all the cookies. The cookies are in the key=value pairs format. Cookies are deleted as soon as the browser is closed but you can specify an expiry date for it.
Syntax
Following is the syntax for −
Setting the cookie property −
document.cookie = newCookie
Here, the newCookie is of type string and is a semicolon separated list of name-value pair. Following are optional values for newCookie.
Parameter Value | Description |
---|---|
expires=date | To specify the date in GMT format. By default the cookies are deleted as soon as the browser is closed. |
path=path: | To specify the directory path on the computer where the cookies are to be stored. Only absolute path to be used . |
domain=domainname | To specify the domain of your website. Current document domain used if not specified. |
Secure | To tell the browser to use https protocol for sending the cookie to the server, |
Example
Let us look at an example for the HTML DOM cookie property −
<!DOCTYPE html> <html> <body> <h1>javascript COOKIE example</h1> <p>Click the below button to create a cookie</p> <button type="button" onclick="cookieCreate()">CREATE</button> <p id="Sample"></p> <script> function cookieCreate(){ var x=document.cookie; x="username=Matt;class=prior;location=USA;expires=Wed, 10 July 2019 12:00:00 UTC"; document.getElementById("Sample").innerHTML="The cookie values are : "+x; } </script> </body> </html>
Output
This will produce the following output −
On clicking the CREATE button −
In the above example −
We have first created a button CREATE that will execute the function createCookie() when clicked by the user −
<button type="button" onclick="cookieCreate()">CREATE</button>
The cookieCreate() function creates a cookie by using the cookie property of the document object. We then set the cookie key-pair values that are semicolon separated. The cookie created is then displayed in the paragraph with id “Sample” using its innerHTML property −
function cookieCreate(){ var x=document.cookie; x="username=Matt;class=prior;location=USA;expires=Wed, 10 July 2019 12:00:00 UTC"; document.getElementById("Sample").innerHTML="The cookie values are : "+x; }