Sunday, 9 October 2016

javascript - JS - Cannot read property 'setAttribute' of null





I am pretty new to javascript and want to code a header of an html site.
JS: when the window width is smaller than 1215px --> left part goes 100% width; right part of the header to 0



I always get the "Cannot read property 'setAttribute' of null " Error!




Please Help!
Code:





if (window.innerWidth < 1215) {
document.getElementById("#headerLeft").setAttribute("style", "width:100%");
document.getElementById("#headerRight").setAttribute("style", "width:0%");
} else {
document.getElementById("#headerLeft").setAttribute("style", "width:50%");

document.getElementById("#headerRight").setAttribute("style", "width:50%");
}

body {
margin:0;
}

header{
height:100px;
width:100%;
}


#headerLeft {
background-color:#FF7043;
height:100px;
float:left;
}

#headerRight {
background-color:#FFFFFF;
height:100px;

float:right;
}

.headerTitle {
font-family:'Roboto', sans-serif;
margin:15px;
font-size:70px;
}

#headerRight .headerTitle {

text-align:left;
color:#FF7043;
font-weight:300;
}

#headerLeft .headerTitle {
text-align:center;
color:#FFFFFF;
font-weight:900;
}






example















example






example



















Answer



It is because all of your calls to document.getElementById are failing to find anything since there aren't any elements with those IDs. Looks like jQuery habits in play, remove the # from your IDs.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...