JavaScript:未捕获的类型错误:无法设置 null 的属性“href”
2016-12-26
16596
通过 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个回答
window.onload=()=>{
var element = document.querySelector('a[href="http://www.google.com"]');
element.href = "http://stackoverflow.com";
};
窗口需要准备好……
Jonas Wilms
2016-12-26
尝试一下
var element = document.querySelector('a');
if(element.href === 'http://www.google.com/'){
element.href = "http://stackoverflow.com";
}
Sharmila
2016-12-26
匹配完整值,并执行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
2016-12-26