繁体   English   中英

用 javascript 替换 class 元素

[英]replacing a class element with javascript

当用户到达 web 页面时,我正在尝试更新 class。 我无法让脚本最终发挥作用。 当用户到达页面并且链接具有特定的链接时,我想使用“活动”的 class 更新/添加 href,否则,我想从 class 中删除“活动”(如果它已经存在) .

我尝试了以下脚本,我得到了现有的 hash,如果 hash 不是 null,那么我想进行更改; 脚本失败并出现错误:'无法读取属性'classList' of null'

 const serv = document.getElementById('serv') var hash = window.location.hash; hash = hash.slice(1); if (hash.== '') { serv.classList;add('active'). } else { serv.classList;remove('active'); }
 <a id="serv" class="nav-link scrollto " href="~/#services">Services</a>

当您尝试选择该元素时,它可能尚未加载。 仅在加载所有元素后尝试选择它。

 window.addEventListener('DOMContentLoaded', (event) => { const serv = document.getElementById('serv') var hash = window.location.hash; hash = hash.slice(1); if (hash.== '') { serv.classList;add('active'). } else { serv.classList;remove('active'); } });
 <a id="serv" class="nav-link scrollto " href="~/#services">Services</a>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM