Onclick将文本添加到div

时间:2013-10-26 16:26:10

标签: javascript html button onclick

我刚开始学习Javascript,但我真的以为我知道这一点。我无法弄清楚为什么它不起作用。我需要它在单击按钮时将格式为2级标题的“此文本”插入theDiv。我已经尝试过各种方式,即使有一个功能。这个例子看起来应该是它的工作方式,但事实并非如此。我必须使用Javascript才能完成这项工作,没有JQuery - 我还不知道。

<html>
  <h1 id="header">Header in progress</h1>
  <body>
    <p>
      <input type="button" id="theButton" value="click me!" onclick="document.getElementById('theDiv').innerHTML('This is new.')">
    </p>
    <h3><div id="theDiv"></div></h3>
  </body>
</html>

3 个答案:

答案 0 :(得分:3)

document.getElementById("theDiv").textContent = 'This is dynamically added text';

答案 1 :(得分:2)

使用document.getElementById('theDiv').innerHTML = 'This is new.'

您需要在id中传递''(quotes) div而innerHTML属性不是函数

Demo

答案 2 :(得分:0)

第一步:获取按钮和html元素。 第二步:在按钮上添加点击监听器 第三步:将文本添加到html元素中。

const btn = document.getElementById('theButton');
const myText = document.getElementById('theDiv');

btn.addEventListener('click', function(){
  const myInsertText = 'Hello World !';
myText.innerHTML = myInsertText;

});
 <button id='theButton'>bouton</button>
 <p id="theDiv"></p>

相关问题