Javascript To HTML
Comparing different ways of inserting html into the page via javascript
by jacobwsmith
HTML
<div id="example"><p>This is a test string with a link to <a href="http://google.com">Google.com</a></p></div>
<div id="test1"></div>
<div id="test2"></div>
<div id="test3"></div>
<div id="test4"></div>
CSS
#example{
border: dotted 1px #ccc;
background-color: #f1f1f1;
}
#test1{
border: solid 1px #ccc;
background-color: red;
}
#test2{
border: solid 1px #ccc;
background-color: yellow;
}
#test3{
border: solid 1px #ccc;
background-color: green;
}
#test4{
border: solid 1px #ccc;
background-color: #ccc;
}
JavaScript
var test1 = function(){
var html = '<p>This is a test string with a link to <a href="http://google.com">Google.com</a></p>';
html += '<ul>';
html += '<li><a href="#">Option 1</a></li>';
html += '<li><a href="#">Option 2</a></li>';
html += '<li><a href="#">Option 3</a></li>';
html += '</ul>';
document.getElementById("test1").innerHTML = html;
}
var test2 = function(){
var ele, ul, li;
ele = document.createElement('p');
ele.innerHTML = 'This is a test string with a link to <a href="http://google.com">Google.com</a>';
ul = document.createElement('ul');
li = document.createElement('li');
li.innerHTML = '<a href="#">Option 1</a>';
ul.appendChild(li);
li = document.createElement('li');
li.innerHTML = '<a href="#">Option 2</a>';
ul.appendChild(li);
li = document.createElement('li');
li.innerHTML = '<a href="#">Option 3</a>';
ul.appendChild(li);
document.getElementById('test2').appendChild(ele);
document.getElementById('test2').appendChild(ul);
}
var test3 = function(){
var html = '<p>This is a test string with a link to <a href="http://google.com">Google.com</a></p>';
html += '<ul>';
html += '<li><a href="#">Option 1</a></li>';
html += '<li><a href="#">Option 2</a></li>';
html += '<li><a href="#">Option 3</a></li>';
html += '</ul>';
$('#test3').append(html);
}
var test4 = function(){
var ele, ul, li;
ele = $('<p>');
ele.html('This is a test string with a link to <a href="http://google.com">Google.com</a>');
ul =$('<ul>');
li = $('<li>');
li.html('<a href="#">Option 1</a>');
ul.append(li);
li = $('<li>');
li.html('<a href="#">Option 2</a>');
ul.append(li);
li = $('<li>');
li.html('<a href="#">Option 3</a>');
ul.append(li);
$('#test4').append(ele);
$('#test4').append(ul);
}
$(document).ready(function() {
test1();
test2();
test3();
test4();
});