Pradeep K P
Pradeep K P

Reputation: 1

JavaScript : Uncaught TypeError: Cannot set property 'href' of null

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>

Upvotes: 0

Views: 17264

Answers (3)

Sharmila
Sharmila

Reputation: 795

Try this

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

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138447

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

the window needs to be ready...

Upvotes: 1

Deep
Deep

Reputation: 9794

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>

Upvotes: 0

Related Questions