Search code examples
javascriptjqueryhrefvar

how to get a specific string in an href in javascript


I am trying to create an onload event where a function compares the current URL to an href and displays content according to the href that is shown. I want to accomplish this by selecting a child from a parent, though I am unsure as to how to get the contents within the href specifically. Here is a bit of the code I have written:

html

<ul id="main-nav">
      <li class="nav active"><a href="#shipping">Shipping</a></li>
      <li class="nav"><a href="#returns">returns</a></li>
      <li class="nav"><a href="#custom">Custom Orders</a></li>
      <li class="nav"><a href="#replacements">Replacements/ Warranty</a></li>
      <li class="nav"><a href="#mostFAQs">Most Frequently Asked Questions</a></li>
      <li class="nav"><a href="#RAD">RAD Principles</a></li>
      <li class="nav"><a href="#environmental">Environmental Stewardship</a></li>
      <li class="nav"><a href="#USA">MADE in the USA</a></li>
</ul>

js

var href = $("#main-nav").children('a');

$("div.faq-container").hide();

if (window.location.href.includes(href)) {
    $("div.faq-container").eq("0").show();
} else (window.location.href.includes(href)) {
    $("div.faq-container").eq("1").show();
}

the main issue I have is that I want to write the line that has

var href = $("#main-nav").children('a');

so that it grabs the contents within the href alone, and nothing else outside of that, so that it would have either "#shipping", "#returns", etc. as its value.


Solution

  • You took the problem by the wrong end. What you need to know is the location.hash to target the right div to display.

    This should be closer:

    var hash = window.location.hash
    
    // Hide all .faq-container
    $("div.faq-container").hide()
    
    // If there is a hash
    if(hash){
      $("#"+hash).show()
    }