gpt4 book ai didi

javascript - 如何更改列表项的innerHTML?

转载 作者:行者123 更新时间:2023-11-28 17:54:01 25 4
gpt4 key购买 nike

好的,我有这段 HTML 代码

<ul class="wsite-menu-default">
<li id="lis1" class="wsite-menu-item-wrap wsite-nav-1" style="position: relative;">
<a href="#" class="wsite-menu-item" style="position: relative;">
Home
</a>
</li>
<li id="lis2" class="wsite-menu-item-wrap wsite-nav-2" style="position: relative;">
<a href="#" class="wsite-menu-item" style="position: relative;">
Images
</a>
</li>
<li id="lis3" class="wsite-menu-item-wrap wsite-nav-3" style="position: relative;">
<a href="#" class="wsite-menu-item" style="position: relative;">
Facilities
</a>
</li>
<li id="lis4" class="wsite-menu-item-wrap wsite-nav-4"
style="position: relative;">
<a href="#" class="wsite-menu-item" style="position: relative;">
Contact
</a>
</li>
</ul>

我想做的是将第一个列表项“Home”的文本更改为“Main”,而不影响元素的功能。到目前为止我已经尝试了很多事情。然而,这是我尝试的最后一件事:

<script>
document.getElementById("lis1").innerHTML = "<a href="#" class="wsite-menu-item" style="position: relative;">Main</a>";
</script>

提前谢谢您。

最佳答案

仅更改 textContent,而不是整个 innerHTML

let elem = document.querySelector('#lis1 a');
elem.textContent = 'Main';
<ul class="wsite-menu-default">
<li id="lis1" class="wsite-menu-item-wrap wsite-nav-1" style="position: relative;">
<a href="#" class="wsite-menu-item" style="position: relative;">
Home
</a>
</li>
<li id="lis2" class="wsite-menu-item-wrap wsite-nav-2" style="position: relative;">
<a href="#" class="wsite-menu-item" style="position: relative;">
Images
</a>
</li>
<li id="lis3" class="wsite-menu-item-wrap wsite-nav-3" style="position: relative;">
<a href="#" class="wsite-menu-item" style="position: relative;">
Facilities
</a>
</li>
<li id="lis4" class="wsite-menu-item-wrap wsite-nav-4" style="position: relative;">
<a href="#" class="wsite-menu-item" style="position: relative;">
Contact
</a>
</li>
</ul>

关于javascript - 如何更改列表项的innerHTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44862180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com