How to append data to div using JavaScript?

前端 未结 11 1740
忘了有多久
忘了有多久 2020-11-22 09:39

I\'m using AJAX to append data to div element, where I fill the div from JavaScript, how can I append new data to the div without losing the previous data found in div?

相关标签:
11条回答
  • 2020-11-22 10:19

    If you are using jQuery you can use $('#mydiv').append('html content') and it will keep the existing content.

    http://api.jquery.com/append/

    0 讨论(0)
  • 2020-11-22 10:25

    IE9+ (Vista+) solution, without creating new text nodes:

    var div = document.getElementById("divID");
    div.textContent += data + " ";
    

    However, this didn't quite do the trick for me since I needed a new line after each message, so my DIV turned into a styled UL with this code:

    var li = document.createElement("li");
    var text = document.createTextNode(data);
    li.appendChild(text);
    ul.appendChild(li);
    

    From https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent :

    Differences from innerHTML

    innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.

    0 讨论(0)
  • 2020-11-22 10:27

    Beware of innerHTML, you sort of lose something when you use it:

    theDiv.innerHTML += 'content';
    

    Is equivalent to:

    theDiv.innerHTML = theDiv.innerHTML + 'content';
    

    Which will destroy all nodes inside your div and recreate new ones. All references and listeners to elements inside it will be lost.

    If you need to keep them (when you have attached a click handler, for example), you have to append the new contents with the DOM functions(appendChild,insertAfter,insertBefore):

    var newNode = document.createElement('div');
    newNode.innerHTML = data;
    theDiv.appendChild(newNode);
    
    0 讨论(0)
  • 2020-11-22 10:28

    java script

    document.getElementById("divID").html("this text will be added to div");
    

    jquery

    $("#divID").html("this text will be added to div");
    

    Use .html() without any arguments to see that you have entered. You can use the browser console to quickly test these functions before using them in your code.

    0 讨论(0)
  • 2020-11-22 10:29

    Even this will work:

    var div = document.getElementById('divID');
    
    div.innerHTML += 'Text to append';
    
    0 讨论(0)
提交回复
热议问题