javascripthtmlwindow.location

Show only elements with a specific id (determened in the url)


I've been working on a coding project and I have been trying to have multiple "pages" in one html file (e.g. awsomesauce.com/page.html#videos and showing only the videos section) while having the same navbar and so far javascript has let me down. Any ideas?

<script>
// Get the current URL (awsomesauce.com/page#videos in this instance)
let url = window.location.href;
// Get the length of the current URL
let urlLength = window.location.href.length;
// Extract the portion of the URL starting from index 21
let  = url.substr(21, urlLength);
</script>

Solution

  • Please look at the URL interface and location.search which would be much more useful than the deprecated substr

    JS alternative to the better CSS solution posted here

    Code is assuming each "page" is a <section id="someID">...</section>

    const showID = location.search;
    if (showID) {
      document.querySelectorAll('section')
        .forEach(section => section.hidden = !section.matches(showID));
    }