How to insert HTML with Javascript?

Asked

Viewed 30,079 times

4

What is the simplest way to insert HTML into an element through Javascript?

  • 2

    for those who are starting I suggest a "little lessons" on this site http://www.w3schools.com/js/js_htmldom_nodes.asp helped me a lot in the beginning

6 answers

7

var element = document.getElementById('element');
element.innerHTML = '<b>Hello World!</b>'

But note that this creates the possibility of security holes if the HTML you want to insert is not static (this is especially truth if the user can control part of the content you want to insert), but it is difficult to post a safer version of the above code without knowing exactly what the face of the HTML you want to insert is like.

  • If you edit your question and post an example of what the HTML you want to insert is like, I can edit my answer to show you how to do it safely.

  • your code example is very simple, if it is the "most" simple to only do with 1 line of code, +1 for the simplicity (efficiency) of the code

2

Use Jquery:

<html>
   <head>
     <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
     <script>
       function addNewBtn(){
          $("body").append("<button>Outro Botão adicionado</button>");
       }
    </script>
  </head>
  <body>
     <button onclick="addNewBtn()">Adicione outro botão !</button>
  </body>
</html>
  • Jquery Library is an extremely fast, clean and semantically elegant way to handle the DOM (Document Object Model), see the http://api.jquery.com API documentation/.

2

Use ``to delimit a string in html

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>
<div id="html"></div>

  • Hello, in the above implementation you have the HTML file already generated and are inserting more information? Or it generates your HTML? I needed to use information I have in a portal to generate an HTML that will serve as a report for the user. I need to build this HTML dynamically. I had already seen an example like this, I tried to do but it does not generate the file, if you can explain to me thank you very much.

1

0

An unconventional way would be to inherit the innerHtml property from the Htmlelements interface.

For example:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Example Custom Elements</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<style>
    .alert {
        padding: 1rem;
        margin: 1rem;
        display: flex;
        align-self: center;
    }
</style>

<body>
    <my-app></my-app>
</body>
<script>
    class MyApp extends HTMLElement {
        connectedCallback() {
            this.render();
        }

        render() {
            this.alerts = [
                'primary',
                'secondary',
                'success',
                'danger',
                'warning',
                'info',
                'light',
                'dark'];

            this.innerHTML = ` ${this.alerts.map(item => `
                <div class="alert alert-${item}" role="alert">
                            A simple ${item} alert—check it out!
                </div>
            `).join('')}`;
        }
    }
    window.customElements.define('my-app', MyApp);
</script>

</html>

0

I believe that using some functions of javascript 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: https://jsfiddle.net/tetbdkpe/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.