JavaScript:未捕获的TypeError:无法设置属性' href'为null

时间:2016-12-26 12:34:06

标签: javascript html

通过javascript更改href时出现此错误。无法通过javascript更改href

<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>

3 个答案:

答案 0 :(得分:0)

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

窗口需要准备好......

答案 1 :(得分:0)

匹配完整值并在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>

答案 2 :(得分:0)

试试这个

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