如何使用javascript在html页面中显示元素?

如何使用javascript在html页面中显示元素?,javascript,html,css,bootstrap-4,Javascript,Html,Css,Bootstrap 4,我有一组硬编码的html元素 <!-- Reciever Message--> <div class="media w-50 ml-auto mb-3"> <div class="media-body"> <div class="bg-primary rounded py-2 px-3 mb-2"

我有一组硬编码的html元素

                    <!-- Reciever Message-->
                <div class="media w-50 ml-auto mb-3">
                    <div class="media-body">
                        <div class="bg-primary rounded py-2 px-3 mb-2"> 
                            <p class="text-small mb-0 text-white">Test chat</p>
                        </div>
                    </div>
                </div>

当我点击按钮时,什么都没有发生?我做错了什么吗?

我看到您正在创建元素div3,它附加了您正在讨论的p,但我没有看到您将它们附加到DOM

所以你需要这样做

document.body.appendChild(div3)


我调整了代码以获得所需的输出

function addText() {
  var p = document.createElement('p');
  p.className = 'text-small mb-0 text-white';
  var inputValue = document.getElementById('message').value;
  var text = document.createTextNode(inputValue);
  p.appendChild(text);

  if (inputValue === '') {
    alert('You must write something!');
  } else {
    var div = document.createElement('div');
    div.className = 'media w-50 ml-auto mb-3';
    var div2 = document.createElement('div');
    div2.className = 'media-body';
    div.appendChild(div2);
    var div3 = document.createElement('div');
    div3.className = 'bg-primary rounded py-2 px-3 mb-2';
    div3.id = 'receive-text';
    div2.appendChild(div3);
    div3.appendChild(p);
    document.body.appendChild(div);
  }
  document.getElementById('message').value = '';
}

您没有使用appendChild。这是唯一的错误。

您缺少对body或其他元素的p的最后附加。啊,是的。。在将所有元素添加到一起直到最后一个之后,它就可以工作了。谢谢
document.body.appendChild(div3)
document.getElementById("#idOfDiv3Parentelement").appendChild(div3)
function addText() {
  var p = document.createElement('p');
  p.className = 'text-small mb-0 text-white';
  var inputValue = document.getElementById('message').value;
  var text = document.createTextNode(inputValue);
  p.appendChild(text);

  if (inputValue === '') {
    alert('You must write something!');
  } else {
    var div = document.createElement('div');
    div.className = 'media w-50 ml-auto mb-3';
    var div2 = document.createElement('div');
    div2.className = 'media-body';
    div.appendChild(div2);
    var div3 = document.createElement('div');
    div3.className = 'bg-primary rounded py-2 px-3 mb-2';
    div3.id = 'receive-text';
    div2.appendChild(div3);
    div3.appendChild(p);
    document.body.appendChild(div);
  }
  document.getElementById('message').value = '';
}