0

I have this function "filename" which gets the name of a file and changes all text with the attribute class='filename' to the name of the file.

For example, in example.html, <p class='filename'></p> would read "example".

Here is the function, which I placed at the end of the body tag (I got the code from here if it helps):

<script type="text/javascript">
function filename() {
    var url = window.location.pathname; // gets the pathname of the file
    var str = url.substring(url.lastIndexOf('/')+1); // removes everything before the filename
    str = str.substring(0, str.length - 5); // removes the extension
    var filename = str.replace(/%20/g, " "); // if the filename has multiple words separated by spaces, browsers do not like that and replace each space with a %20. This replace %20 with a space.
    document.getElementsByClassName("filename").innerHTML = filename;
}
</script>

In example.html, I added the code <title class="filename"></title> and also <p class="filename"></p>, but the function does not work. I tried adding onload="filename()" to both the body and head tags but nothing changed.

Hasan
  • 11
  • 3

1 Answers1

-1

Try this :

document.addEventListener('DOMContentLoaded', function() {
    filename();
});

function filename() {
    var url = window.location.pathname; // gets the pathname of the file
    var str = url.substring(url.lastIndexOf('/')+1); // removes everything before the filename
    str = str.substring(0, str.length - 5); // removes the extension
    var filename = str.replace(/%20/g, " "); // if the filename has multiple words separated by spaces, browsers do not like that and replace each space with a %20. This replace %20 with a space.
    document.getElementsByClassName("filename").innerHTML = filename;
}
snd
  • 133
  • 6