How to append data to div using JavaScript?

前端 未结 11 1756
忘了有多久
忘了有多久 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:05

    Why not just use setAttribute ?

    thisDiv.setAttribute('attrName','data you wish to append');
    

    Then you can get this data by :

    thisDiv.attrName;
    
    0 讨论(0)
  • 2020-11-22 10:06

    The following method is less general than others however it's great when you are sure that your last child node of the div is already a text node. In this way you won't create a new text node using appendData MDN Reference AppendData

    let mydiv = document.getElementById("divId");
    let lastChild = mydiv.lastChild;
    
    if(lastChild && lastChild.nodeType === Node.TEXT_NODE ) //test if there is at least a node and the last is a text node
       lastChild.appendData("YOUR TEXT CONTENT");
    
    0 讨论(0)
  • 2020-11-22 10:09

    you can use jQuery. which make it very simple.

    just download the jQuery file add jQuery into your HTML
    or you can user online link:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    

    and try this:

     $("#divID").append(data);
    
    0 讨论(0)
  • 2020-11-22 10:10

    If you want to do it fast and don't want to lose references and listeners use: .insertAdjacentHTML();

    "It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element. This, and avoiding the extra step of serialization make it much faster than direct innerHTML manipulation."

    Supported on all mainline browsers (IE6+, FF8+,All Others and Mobile): http://caniuse.com/#feat=insertadjacenthtml

    Example from https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

    // <div id="one">one</div>
    var d1 = document.getElementById('one');
    d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
    
    // At this point, the new structure is:
    // <div id="one">one</div><div id="two">two</div>
    
    0 讨论(0)
  • 2020-11-22 10:12

    Try this:

    var div = document.getElementById('divID');
    
    div.innerHTML += 'Extra stuff';
    
    0 讨论(0)
  • 2020-11-22 10:15

    Using appendChild:

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

    Using innerHTML:
    This approach will remove all the listeners to the existing elements as mentioned by @BiAiB. So use caution if you are planning to use this version.

    var theDiv = document.getElementById("<ID_OF_THE_DIV>");
    theDiv.innerHTML += "<YOUR_CONTENT>"; 
    
    0 讨论(0)
提交回复
热议问题