简体   繁体   中英

insert/remove HTML content between div tags

how can I insert some HTML code between <div id="mydiv">...</div> using javascript?

Ex: <div id="mydiv"><span class="prego">Something</span></div> its about 10 lines of html of most. thank you

如果您要替换 div 的内容并将 HTML 作为字符串,则可以使用以下内容:

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

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>");
// Build it using this variable
var content = "<span class='prego'>....content....</span>"; 
// Insert using this:
document.getElementById('mydiv').innerHTML = content;

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'));
 document.getElementById("mydiv").innerHTML = "<span class='prego'>Something</span>";

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

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

Javascript

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

jQuery

$("#mydiv").append('<span class="prego">Something</span>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM