I have a calendar on my web page, and this script will add a class if the day on the task matches the current day. This work if i do have any tasks on that current day. But if i dont, it will give me an error on this current script and all the others script on my web page making the web page useless. So the question is, how to i make this script just ignore and do nothing if the if statement doesn't return anything?
var d = new Date(2019, 1, 24); var month = d.getMonth() + 1; //.getMonth() is 0-11 var day = d.getDate(); if (day < 10) { day = '0' + dd; } if (month < 10) { month = '0' + month; } var mydivs = document.getElementsByClassName("mydiv"); for(var i = 0; i < mydivs.length; i++) { if (mydivs[i].children[0].innerHTML == `${day}.${month}`) { mydivs[i].className += " today"; } }
.today { border: 2px solid red; color: red; }
<div class="mydiv"> <span class="date-display-single day" property="dc:date" datatype="xsd:dateTime" content="2019-02-24T11:30:00+01:00">24.02</span> </div> <div class="mydiv"> <span class="date-display-single day" property="dc:date" datatype="xsd:dateTime" content="2019-02-25T11:30:00+01:00">25.02</span> </div>
You just need to length check the children before trying to access the [0]
child, or else you get an index out of bounds error.
var d = new Date(2019, 1, 24); var month = d.getMonth() + 1; //.getMonth() is 0-11 var day = d.getDate(); if (day < 10) { day = '0' + dd; } if (month < 10) { month = '0' + month; } var mydivs = document.getElementsByClassName("mydiv"); for(var i = 0; i < mydivs.length; i++) { if (mydivs[i].children.length && mydivs[i].children[0].innerHTML == `${day}.${month}`) { mydivs[i].className += " today"; } }
.today { border: 2px solid red; color: red; }
<div class="mydiv"> </div> <div class="mydiv"> <span class="date-display-single day" property="dc:date" datatype="xsd:dateTime" content="2019-02-24T11:30:00+01:00">24.02</span> </div> <div class="mydiv"> <span class="date-display-single day" property="dc:date" datatype="xsd:dateTime" content="2019-02-25T11:30:00+01:00">25.02</span> </div>
It seems to me, that if you change line #6 of JS code to day = '0' + day;
, then you will have no problem. Variable dd
which you use is not initialized in the scope.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.