Search code examples
javascriptselectors-api

document.querySelectorAll("a") returning blank nodelist with # url


I have some javascript that adds the text of a variable (c) to href of all links identified by the querySelectorAll("a").

This normally works fine.

The problem is, when I go to the URL of this page, and add a hash/pound symbol with anything after it, such as "#something" the querySelectorAll("a") returns a blank nodelist. Here is my code:

$(document).ready(function() {
   m = document.querySelectorAll("a");

   m.forEach(function(item){
        v = item.getAttribute("href");      
        item.setAttribute( "href", v.concat(window.c) );
   });

})

And here is how I found out the node list was returning blank:

<p id="p1"></p>

<script type="text/javascript">
$(document).ready(function() {
   m = document.querySelectorAll("a");

   m.forEach(function(item){
        v = item.getAttribute("href");      
        document.getElementById("p1").innerHTML = v + " ";
        item.setAttribute( "href", v.concat(window.c) );
   });

})
</script>

This returns "null " in the paragraph id="p1".

Any ideas why querySelectorAll doesn't seem to work, in Chrome at least, when loading a url with a "#" in it?

Update:

CertainPerformance wanted me to post any additional scripts I had that depended on the #, so here it is:

/* This code adds or removes #_numbers to the end of the URL if the user clicks a accordion link */

if(window.location.href.indexOf("#") > -1) {
  h = window.location.href.indexOf("#");
  i = window.location.href.length;
  j = window.location.href.substring(h, i);
  x = j
}else{
  x = "#_"
}

$(document).ready(function(){
  $("#heading1").click(function(){

    //when heading link is clicked, it toggles the section
    $("#section1").toggle();

    if(window.x.includes("1")){
      //if x has a 1 in it, get rid of the 1
        window.x = window.x.replace("1", ""); 
    }
    else{
        window.x = window.x.concat("1"); //if x doesn't have a 1 in it, add a 1
    }    

    window.x = window.x.replace("#_", ""); //remove multiple instances of #_ if there are any

    y = "#_"

    window.x = y.concat(window.x) // add #_ to the beginning of x

    $('a[href]').each(function(){

        var oldUrl = $(this).attr("href"); // set oldUrl to link above

        if(oldUrl.includes("#_")){
            oldUrl = oldUrl.replace("#_", ""); 
        }
        if(oldUrl.includes("1")){
            oldUrl = oldUrl.replace("1", ""); 
        }

        var newUrl = oldUrl.concat(window.x); // for each link, concatenate it with x 

        $(this).attr("href", newUrl); // Set herf value

            document.getElementById("heading1").href = window.x;
    });  
  });
});

Solution

  • Gabriele Petrioli fixed it in the comments. He said:

    There probably are some a tags without a href. Try using m = document.querySelectorAll("a[href]");