Tania Marinova
Tania Marinova

Reputation: 1898

Exception Unable to set property 'href' of undefined or null reference when

The problem is this: I try to dynamically change the innerHTML and href of an LINk in a function CheckCookie which is executed in body - onload. Here is the function:

function checkCookie()
{
    var username = getCookie("username");

    if (username != null && username != "")
    {       
        document.getElementById("firstlink").href = "http://localhost:8080/newLogIN/probalassfinalwithoutstyle.html";
        document.getElementById("firstlink").innerHTML = "Go to my lesson";       
    }
}

also I have another jquery function which is executed on document ready

function DropDown(el) {
    this.dd = el;
    this.initEvents();
}
DropDown.prototype = {
    initEvents: function() {
        var obj = this;

        obj.dd.on('click', function(event) {
            $(this).toggleClass('active');
            event.stopPropagation();
        });
    }
}


$(function() {

    var dd = new DropDown($('#dd'));

    $(document).click(function() {
        // all dropdowns
        $('.wrapper-dropdown-3').removeClass('active');
    });

});

In my body I've got this

<body onload="CheckCookie()">
    <div id="dd" class="wrapper-dropdown-3">LoGG
        <ul class="dropdown">
            <li><a href="#" id="firstlink">Gismo Account</a> </li>

    </div>
</body>

Everything works as I want but when I add

document.getElementById("dd").innerHTML = "Hi," + getCookie("username");  

to change the InnerHtML of dd div it gives me an exception

SCRIPT5007: Unable to set property 'href' of undefined or null reference

Upvotes: 0

Views: 4810

Answers (1)

Chris
Chris

Reputation: 27619

When you run document.getElementById("dd").innerHTML = "Hi," + getCookie("username"); you are replacing the content of the dd element entirely. This includes the firstlink anchor. Thus when you come to change that link there is no element with that ID and thus it fails with that error.

Upvotes: 2

Related Questions