0

While changing the href through javascript getting this error.Not able to change the href through javascript

<script type="text/javascript">
    var element = document.querySelector('a[href="www.google.com"]');
    element.href = "http://stackoverflow.com";
  </script>
<div id="footer">
    <ul>
      <li>
        <a target="_blank" href="http://www.google.com">Google</a> 
      </li>
    </ul>
  </div>
Pradeep K P
  • 1
  • 1
  • 1
  • Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element). Also, verify that `www.google.com` is the actual value you want to match, or use `href*=` instead of `href=`. – Sebastian Simon Dec 26 '16 at 12:38

3 Answers3

1
window.onload=()=>{
   var element = document.querySelector('a[href="http://www.google.com"]');
   element.href = "http://stackoverflow.com";
 };

the window needs to be ready...

Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
0

Match the complete value and execute the script after the div

document.querySelector('a[href="http://www.google.com"]')

<div id="footer">
    <ul>
      <li>
        <a target="_blank" href="http://www.google.com">Google</a> 
      </li>
    </ul>
  </div>

<script type="text/javascript">
    var element = document.querySelector('a[href="http://www.google.com"]');
    element.href = "http://stackoverflow.com";
  </script>
Deep
  • 9,054
  • 2
  • 14
  • 30
0

Try this

 var element = document.querySelector('a');
 if(element.href === 'http://www.google.com/'){
  element.href = "http://stackoverflow.com";
 }
Sharmila
  • 725
  • 4
  • 11