将Class添加到现有div元素中



我想在购物车图标(Wooccommerce(旁边显示我的帐户部分的图标。

为了做到这一点,我想添加另一个名为"的类;et账户信息";到现有的div id元素。HTML代码如下所示:

<div id="et-top-navigation">
<nav id="top-menu-nav">…</nav>
<a href="https://example.com/cart/" class="et-cart-info">…</a>
<div id="et_mobile_nav_menu"></div>
</div>

最终它应该是这样的。新类应该显示在第一个a标记的正下方。

<div id="et-top-navigation">
<nav id="top-menu-nav">…</nav>
<a href="https://example.com/cart/" class="et-cart-info">…</a>
<a href="https://example.com/my-account/" class="et-account-info">…</a>
<div id="et_mobile_nav_menu"></div>
</div>

我尝试使用一个根本不起作用的Javascript函数:

<script>
var element = document.getElementById("et-top-navigation");
element.classList.add("et-account-info");
</script>

有什么想法为什么不起作用吗?或者有没有一种更平滑的方法来使用php?

我假设您正在<head></head>标记中添加脚本。不幸的是,像这样添加的脚本将在加载/解析文档的其余部分之前运行。在检查元素之前,您需要告诉代码等待DOM被完全加载和解析。

function addClassToElement() {
var element = document.getElementById("et-top-navigation");
element.classList.add("et-account-info");
}
// Check if document is already loaded. If so, run the function.
// Otherwise, wait for the DOMContentLoaded event to fire before running it.
if (document.readyState === "complete" || document.readyState === "interactive") {
addClassToElement();
} else {
document.addEventListener("DOMContentLoaded", addClassToElement);
}

但是,根据您要查找的结果,您的代码是不完整的。这只会向ID为et-top-navigationdiv元素添加一个类。

尝试添加(提示:追加(您要添加的新元素。

最新更新