如何使用 Javascript 更改 <div> 标签内的文本?

How do I change text within <div> tags with Javascript?

我需要一些帮助来编辑 HTML 和 JavaScript 中的元素。是否可以将 "text" 更改为 javascript?我试过使用 document.getElementById 但我认为我做的不正确。

使用您在 css:

中使用的查询获取元素
var element = document.querySelector('div.header');

使用 textContent 属性 更改内容:

element.textContent = "New Content;"

正在向内容添加图片:

document.querySelector('div.header').innerHTML = "<img src='smiley.gif' alt='Smiley face' height='42' width='42'>";

带有 "press me" 按钮的简单示例调用函数来更改文本

<html>
<script>
    function changeText(){
        document.getElementById("header").innerHTML = "changed text";
    };
</script>
<body>
    <div id="header">text</div>
    <button onclick="changeText()">press me</button>
</body>

<html>
 <script>
  function changeText(){
   document.getElementById("header").innerHTML = "changed text";
  };
 </script>
 <body>
  <div id="header">text</div>
  <button onclick="changeText()">press me</button>
 </body>
</html>

如果querySelectorAllgetElementsbyClassName有很多方法可以改变文本。

我的回答是,您必须考虑 HTML 文档的结构。

每个ID只能使用一次。最好使用 data-lb="detail" 等,类 用于 div´s

请不要将此视为答案,仅作为提示。

您可以尝试这样的操作 -

<button id="click">
CLICK
</button>
<div class="header" id="textChange">Text</div>

然后在你的 JS 中 -

$( "#click" ).click(function() {
$( "#textChange" ).replaceWith( "<h2>New heading</h2>" );
});