Search code examples
javascriptstylestypeerror

js.js:14 Uncaught TypeError: Cannot read property 'style' of null


I am a beginner in JavaScript and there is an error in my code. could anyone can give me any suggestion for it?

window.onload = function() {
  value1.style.display = "block";
  value2.style.display = "none";
  value3.style.display = "none";
  value4.style.display = "none";
}

if(window.localStorage.getItem('valuestate') === null) {
    setValue ('value1');
    value1.style.display = "block";
} else {
    var valueItem = readValue()
    document.getElementById('valueItem').style.display = "block";
}

function setValue (clickedOn) {
    clearValue();
    window.localStorage.setItem('valuestate', clickedOn);
    document.getElementById(clickedOn).style.display = "block";
}

function clearValue () {
    var value = document.getElementsByClassName('container');
    for (var loop = 0; loop < value.length; loop++) {
        value[loop].style.display = 'none';
    }
}

function readValue () {
    console.log( window.localStorage.getItem('valuestate') );
    return window.localStorage.getItem('valuestate');
}

function doValue(clickedElement) {
    setValue(clickedElement);
    document.getElementById(clickedElement).focus();
}

HTML:

<div class="collapse navbar-collapse" id="navbarNavDropdown">
    <ul class="navbar-nav ml-auto">
        <li class="nav-item" id="menu1">
            <a class="nav-link" href="#" onclick="doValue('value1')" accesskey="h">Profile<span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item" id="menu2">
            <a class="nav-link" href="#" onclick="doValue('value2')" accesskey="s">Skills</a>
        </li>
        <li class="nav-item" id="menu3">
            <a class="nav-link" href="#" onclick="doValue('value3')" accesskey="p">Projects</a>
        </li>
        <li class="nav-item" id="menu4">
            <a class="nav-link" href="#" onclick="doValue('value4')" accesskey="x">Experiences</a>
        </li>
    </ul>
</div>

and the error is in:

var valueItem = readValue()
document.getElementById('valueItem').style.display = "block";

Solution

  • First of all, don't use the name js.js. It's just bad.

    This should fix your issue:

    var valueItem = readValue() 
    document.getElementById(valueItem).style.display = "block";
    

    Problem:

    You were passing the parameter valueItem "as a string" to document.getElementById() which is a variable.