如何更改列表项的innerHTML?

时间:2017-07-01 14:43:13

标签: javascript html

好的,所以我有这个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>

我正在尝试做的是更改第一个项目的文本&#34; Home&#34;到&#34; Main&#34;而不影响元素的功能。到目前为止,我尝试过很多东西。但是,这是我尝试的最后一件事:

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

提前谢谢。

1 个答案:

答案 0 :(得分:3)

仅更改textContent,而不是整个innerHTML

&#13;
&#13;
let elem = document.querySelector('#lis1 a');
    elem.textContent = 'Main';
&#13;
<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>
&#13;
&#13;
&#13;