Home Ask Login Register

Developers Planet

Your answer is one click away!

Zerh Ariel February 2016

Javascript - Can I display the value of a cookie in HTML?

I have a bootstrap website and I stock user information in cookies with the plugin JS-cookie.

Can I show the value of the cookie in the HTML with classic JS/Jquery or do I have to use a framework like Angular ?


I use js-cookie https://github.com/js-cookie/js-cookie

So my code is, in the head page :

         <script>Cookies.set('money', '200', { expires: 7 });</script>

and in the body :

       <p> You have  <script>Cookies.get('money')</script> dollars </p>


Barmar February 2016

You don't just insert a script in the middle of HTML to get the result of a function. The script has to perform an operation to put a value into the DOM.

<p You have <span id="amount"></span> dollars </p>
var amount = Cookies.get('money');
document.getElementById('amount').textContent = amount;

threed February 2016

In native JavaScript, you can do the following. Note: this doesn't seem to work on Stackoverflow because of a security restriction, but it does seem to work in CodePen.

var arr = document.cookie.split(';'),
    cookies = {};
for(var i=0; i < arr.length; i++){
  var parts = arr[i].split('=');
  if(parts.length !== 2) continue;
  cookies[parts[0].trim()] = parts[1];

document.getElementById('out').textContent = cookies['myCookieKey'];
<div id="out"></div>


Using the JS-Cookie code:

<p>You have <span id="amount"></span> dollars</p>

document.getElementById('amount').textContent = Cookies.get('money');

Post Status

Asked in February 2016
Viewed 2,843 times
Voted 5
Answered 2 times


Leave an answer

Quote of the day: live life