0

I seem to be able to retrieve the value of the cookie but the style of the corresponding ID isn't changed. What am I missing?

    function getCookie(name) {
        var cookieName = document.cookie;
        var prefix = name + "=";
        var begin = cookieName.indexOf("; " + prefix);
        if (begin == -1) {
            begin = cookieName.indexOf(prefix);
            if (begin != 0) return null;
        } else begin += 2;
        var end = cookieName.indexOf(";", begin);
        if (end == -1) end = cookieName.length;
        return unescape(cookieName.substring(begin + prefix.length, end));
    }
    var value = getCookie('nameCookie');
    document.getElementById(value).style.height = "10%";

following code also doesn't work

    var value = getCookie('nameCookie');
    if (value == 'test') {
          document.getElementById('test').style.height = "10%";
    }
4
  • If you console.log(value) does it contains the ID you are expecting Commented Mar 14, 2012 at 23:05
  • 1
    @TimWickstrom.com, he say he seems to have retrieved the value Commented Mar 14, 2012 at 23:07
  • Missed that, try console.log(document.getElementById(value)); What kind of Element is it? Is it a block element, can it have 10% height? is the parent height defined so the browser can calculate 10%? Commented Mar 14, 2012 at 23:12
  • The element is an image of which the original size is 5%. Commented Mar 14, 2012 at 23:16

1 Answer 1

3

Since you seem to be able to retrieve the value of the cookie the problem is that when the code is running, it cannot find the element because the DOM is not ready yet. Make sure the script is running, after the element is loaded.

Just place your script block just before closing the </body>.

Sign up to request clarification or add additional context in comments.

11 Comments

doesn't seem to be any difference
Good call! Spoiled by my own coding habits was not even thinking about if the dom was ready!
@TimD'Haene, Do you have an element with id what the cookies values is?
yes, even if I changed the getElementById to getElementById('idName') and put the whole thing in an if statement, it still isn't working
@TimD'Haene, Paste your html on pastebin and post the link on your post. I want to take a look at it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.