0

I have some php code to echo a list of files in a directory. It works fine, but then I need to use Javascript to hide them after 5 seconds, but for some reason the script doesn't work. Do you know what I need to fix?

 $dir = "/var/www/files/";
    $list = preg_grep('/^([^.])/', scandir($dir));
    foreach (preg_grep('/^([^.])/', scandir($dir)) as $list)
    echo "<span class='list' style='color:red'>$list</span>"."<br>";
    echo "<script>
           setTimeout(function () {
           document.getElementsByClassName('list').style.display='none';}, 5000);
           </script>";
  • this is not enough information - your JS script will start once the DOM content was loaded. have a look here: https://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery – messerbill Jan 06 '19 at 20:11
  • can you suggest a solution? also i think the thread you linked is about jquery –  Jan 06 '19 at 20:12
  • like i said - this is not enough information. What does your complete HTML output look like? – messerbill Jan 06 '19 at 20:13

1 Answers1

1

I think the problem has to do with trying to manipulate the return value of document.getElementsByClassName. The object returned from this method call is an HTMLCollection, which is array-like and definitely not an HTMLElement.

You will want to loop over your collection and then do the ELEMENT.style.display = 'none'; call. Currently the way you have it set up is more of a jQuery style operation, where calling .style.display = 'none' applies to each element of the collection, but because you're doing vanilla JavaScript, you have to do it manually.

In your JavaScript I would do something like this:

const collection = document.getElementsByClassName('list');
[ ...collection ].forEach(element => {
    element.style.display = 'none';
});

I did the [ ...collection ] deal because an HTMLCollection doesn't have native array methods, and so to avoid using a for loop I made it an array (oddly, it has a Symbol.iterator property, so it's easy to convert to an array.

Ryan Dabler
  • 301
  • 3
  • 8