Jack Vawdrey Jack Vawdrey - 1 year ago 80
HTML Question

Have link appear only if href file exists

I have a generic index.html file that has an unordered list of links. I only want the links to be visible if the file that they link to exists.

<li><a class="button" href="text-1.htm">Text 1</a></li>
<li><a class="button" href="text-2.htm">Text 2</a></li>
<li><a class="button" href="text-3.htm">Text 3</a></li>

Is this possible with JavaScript, or would I have to use PHP?

Answer Source

I would personally be using PHP for this, but that's just my opinion, if someone else has a better JS solution, use that instead!

Here is the PHP version I would use:

    echo '<ul>';
    $files = ['text-1.htm', 'text-2.htm', 'text-3.htm'];
    foreach($files as $file) {
        if (file_exists($file)) {
            $file_clean = explode('.', $file);
            $file_clean = str_replace('-', ' ', $file_clean[0]);
            $file_clean = ucfirst($file_clean);
            echo '<li><a class="button" href="' . $file . '">' . $file_clean . '</a></li>';
    echo '</ul>';

Try that, see how it goes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download