search

Home  >  Q&A  >  body text

How to append text inside a div element?

<p>I am using AJAX to append data to a <code><div></code> element, which I populate via JavaScript. How do I append new data to <code><div></code> without losing the previous data within it? </p>
P粉567112391P粉567112391471 days ago483

reply all(2)I'll reply

  • P粉087951442

    P粉0879514422023-08-22 09:15:10

    Use appendChild:

    var theDiv = document.getElementById("<ID_OF_THE_DIV>");
    var content = document.createTextNode("<YOUR_CONTENT>");
    theDiv.appendChild(content);

    Use innerHTML:
    As @BiAiB reminds me, this method will remove all listeners for existing elements. So if you plan to use this version, please proceed with caution.

    var theDiv = document.getElementById("<ID_OF_THE_DIV>");
    theDiv.innerHTML += "<YOUR_CONTENT>";

    reply
    0
  • P粉190443691

    P粉1904436912023-08-22 00:14:03

    Try this:

    var div = document.getElementById('divID');
    
    div.innerHTML += '额外的内容';

    reply
    0
  • Cancelreply