如何更改<a> tag in html

时间:2017-07-21 17:26:15

标签: javascript html

Considering the following code:

<li><a href="#" id="vm1">LA1</a></li>

It is in an html file and its innertext is LA1 as is shown above. Now I want to change the value of the innertext of the above tag through the following code:

document.getElementById("vm1").innerHTML= "LA2";

It didn't work. I thought that it might be the browser I am utilizing (chrome) does not support innerHTML. So I tried an another way:

document.getElementById("vm1").innerText = "LA2"

It did not work either. So what should I to to set the innertext of an tag through js.

3 个答案:

答案 0 :(得分:0)

尝试包装操作您的内容的代码。我怀疑你在锚定之前尝试这个吗?

document.addEventListener("DOMContentLoaded", function(event) {
  document.getElementById("vm1").innerText = 'works!'
});

答案 1 :(得分:0)

问题很可能是你的脚本在html运行之前运行,如果是这种情况,你应该在html之后移动代码,或者添加一个eventlistener,它监听dom加载时的方式如下:

选项1 - 将代码移至html下面

<body>
  <ul>
    <li><a href="" id="vm1"></a></li>
  </ul>
  <script>
    document.getElementById("vm1").innerText = "LA2";
  </script>
</body>

选项2 - 在DOMContentLoaded侦听器中包装代码

document.addEventListener('DOMContentLoaded', e => {
  document.getElementById("vm1").innerText = "LA2";
});

答案 2 :(得分:-1)

data.table

应该工作