What is the simplest way to insert HTML into an element using Javascript?
What is the simplest way to insert HTML into an element using Javascript?
var element = document.getElementById('element');
element.innerHTML = '<b>Hello World!</b>'
But note that this creates the possibility of security breaches if the HTML you want to insert is not static (this is especially true if the user can control some of the content you want to insert) but it's hard to post a more secure version of the above code without knowing exactly what the HTML face is that you want to insert.
Use Jquery:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script><script>functionaddNewBtn(){$("body").append("<button>Outro Botão adicionado</button>");
}
</script>
</head>
<body>
<button onclick="addNewBtn()">Adicione outro botão !</button>
</body>
</html>
If you use Jquery and the content is dynamic
$( "#nomedaDiv" ).load( "teste.html" );
Use ''
to delimit a string in html. behaving it in a variable '.
var html = '
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 200px;
background-color: #f1f1f1;
border: 1px solid #555;
}
li a {
display: block;
color: #000;
padding: 8px 16px;
text-decoration: none;
}
li {
text-align: center;
border-bottom: 1px solid #555;
}
li:last-child {
border-bottom: none;
}
li a.active {
background-color: #4CAF50;
color: white;
}
li a:hover:not(.active) {
background-color: #555;
color: white;
}
</style>
</head>
<body>
<h2>Vertical Navigation Bar</h2>
<p>In this example, we center the navigation links and add a border to the navigation bar.</p>
<ul>
<li><a class="active" href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</body>
</html>
';
$('#html').html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="html"></div>
I think using some javascript functions is the best option. Use for example:
var divEl = document.createElement("div")
var textEl = document.createTextNode("Meu texto vai aqui")
divEl.appendChild(textEl)
document.getElementById("meu_target").appendChild(divEl)
You can see an example in this fiddle: link