如何替换香草JS上的className?

时间:2020-03-10 09:00:50

标签: javascript html css

如何将className(列表)替换为Javascript?我有以下代码:

document.addEventListener("DOMContentLoaded", (e) => {
    const url = window.location;
    let urlReq = url.href;
    if(urlReq.includes('/home')){
        document.getElementById('default-sidenav-menu').className.replace('sidenav-main nav-expanded nav-lock nav-collapsible  sidenav-active-rounded  sidenav-dark', 'sidenav-main nav-collapsed nav-collapsible  sidenav-active-rounded  sidenav-dark');
        console.log(document.getElementById('default-sidenav-menu').className);
    }
});

这是我的html:

<aside class="sidenav-main nav-expanded nav-lock nav-collapsible  sidenav-active-rounded  sidenav-dark" id="default-sidenav-menu">
    <div class="brand-sidebar">
    ...
</aside>

但是在加载页面时,我仍然得到默认的className:sidenav-main nav-expanded nav-lock nav-collapsible sidenav-active-rounded sidenav-dark

我犯了什么错误?

2 个答案:

答案 0 :(得分:2)

您无需替换,只需将字符串类分配给className属性:

Element接口的className属性获取并设置指定元素的class属性的值。

语法:

elementNodeReference.className = cName;

位置:

cName是一个字符串变量,表示当前元素的类或用空格分隔的类。

演示:

document.addEventListener("DOMContentLoaded", (e) => {
  // other code
  document.getElementById('default-sidenav-menu').className = 'sidenav-main nav-expanded nav-lock nav-collapsible  sidenav-active-rounded  sidenav-dark', 'sidenav-main nav-collapsed nav-collapsible  sidenav-active-rounded  sidenav-dark';
  console.log(document.getElementById('default-sidenav-menu').className);
  // other code
});
<aside class="nav-lock nav-collapsible" id="default-sidenav-menu">
    <div class="brand-sidebar">
    </div>
</aside>

答案 1 :(得分:2)

document.getElementById('default-sidenav-menu').className.replace

这意味着您要用另一个字符串替换该字符串,因为“ className”只是一个字符串。

document.body.className.constructor.name
=> "String"

如果要替换它,则应分配新的类名。

document.getElementById('default-sidenav-menu').className = 
 document.getElementById('default-sidenav-menu').className.replace("something", "something_new");