insert/remove HTML content between div tags

后端 未结 7 1948
渐次进展
渐次进展 2020-12-30 01:22

how can I insert some HTML code between

...
using javascript?

Ex:

相关标签:
7条回答
  • 2020-12-30 01:35

    That's really kind of an ambiguous request. There are many ways this can be accomplished.

    document.getElementById('mydiv').innerHTML = '<span class="prego">Something</span>';
    

    That is the simplest. OR;

    var spn = document.createElement('span');
    spn.innerHTML = 'Something';
    spn.className = 'prego';
    document.getElementById('mydiv').appendChild(spn);
    

    Preferred to both of these methods would be to use a Javascript library that creates shortcut methods for the simple things like this, such as mootools. (http://mootools.net)

    With mootools this task would look like:

    new Element('span', {'html': 'Something','class':'prego'}).inject($('mydiv'));
    
    0 讨论(0)
  • 2020-12-30 01:38

    If you're replacing the contents of the div and have the HTML as a string you can use the following:

    document.getElementById('mydiv').innerHTML = '<span class="prego">Something</span>';
    
    0 讨论(0)
  • 2020-12-30 01:42

    document.getElementById('mydiv').innerHTML = 'whatever';

    0 讨论(0)
  • 2020-12-30 01:45

    A simple way to do this with vanilla JavaScript would be to use appendChild.

    var mydiv = document.getElementById("mydiv");
    var mycontent = document.createElement("p");
    mycontent.appendChild(document.createTextNode("This is a paragraph"));
    mydiv.appendChild(mycontent);
    

    Or you can use innerHTML as others have mentioned.

    Or if you would like to use jQuery, the above example could be written as:

    $("#mydiv").append("<p>This is a paragraph</p>");
    
    0 讨论(0)
  • 2020-12-30 01:52
     document.getElementById("mydiv").innerHTML = "<span class='prego'>Something</span>";
    

    Should do it. If you are willing to use jQuery it could be easier.

    0 讨论(0)
  • 2020-12-30 01:54
    // Build it using this variable
    var content = "<span class='prego'>....content....</span>"; 
    // Insert using this:
    document.getElementById('mydiv').innerHTML = content;
    
    0 讨论(0)
提交回复
热议问题