0

Okay, so here is some javascript I wrote for a client. It's intention is to control which element is showing first depending on the day of the week. However, I have an issue that if no content is available for a specific day the element returns the string "Not found any post".

The last few lines of the code get the element's location and my intention is to use this to hide the parent container. Any advice would be much appreciated!

var d = new Date();
var dayInt = d.getDay();
var slides = document.getElementsByClassName("eventDisplay");
var showInt = 7;
var counter = 0;
console.log('started: ' + showInt);
console.log(slides.length);
for(var i = 0; i < slides.length; i++)
{
    console.log('loop');
    if(i == dayInt || (showInt < 7 && counter < 7)){ //if equal OR if showInt has been changed
        console.log('true'); 
        if(showInt > 0){ //and if not showing more than 7
            slides[i].style.display = 'none';
            showInt = showInt - 1;
            counter = counter + 1;
            console.log('reached: ' + showInt);
        }
    }
}

var position = document.documentElement.innerHTML.indexOf('Not found any post');
console.log(position);
position.innerHTML = '';

console:

started: 7
14
loop
true
reached: 6
loop
true
reached: 5
loop
true
reached: 4
loop
true
reached: 3
loop
true
reached: 2
loop
true
reached: 1
loop
true
reached: 0
loop
23837
J Dorrian
  • 206
  • 3
  • 15
  • What's the point of this `document.documentElement.innerHTML.indexOf('Not found any post');` ? - as in what is it that you're hoping it accomplishes? – zfrisch Feb 28 '18 at 17:00
  • 1
    Seems like the point is to search the entire dom for that text, then hide its parent element if located. – James Feb 28 '18 at 17:01
  • I think searching innerhtml is not a good technique, because as you discovered you have no easy way to get the parent element from some numeric position. Check the xpath technique used in [this answer](https://stackoverflow.com/a/29289196/535480) – James Feb 28 '18 at 17:09

1 Answers1

0

Solution: Check the innerHTML of the component's you are displaying. Don't know why I didn't think of this sooner.

var d = new Date();
var dayInt = d.getDay();
var slides = document.getElementsByClassName("eventDisplay");
var showInt = 7;
var counter = 0;
console.log('started: ' + showInt);
console.log(slides.length);
for(var i = 0; i < slides.length; i++)
{
    console.log('loop');
    if(i == dayInt || (showInt < 7 && counter < 7)){ //if equal OR if showInt has been changed
        console.log('true'); 
        if(showInt > 0){ //and if not showing more than 7
            if(slides[i].innerHTML.indexOf('Not found any post') > 0){
                //do nothing
            } else { 
                slides[i].style.display = 'block';
            }

            showInt = showInt - 1;
            counter = counter + 1;
            console.log('reached: ' + showInt);
        }
    }
}
J Dorrian
  • 206
  • 3
  • 15