How to insert a div into a specific div using Javascript

Asked

Viewed 287 times

1

This is my code, I want to insert it into a div with the specific id. But right now I’m having a hard time getting him to show up on the div that I want.

var html =
  '<div class="card">' +
      '<div class="poster"><img id="id00" src=""></div>' +
      '<div class="details">' +
        '<h6>Post name<br><span><a class="link" href="#" target="_blank"></a></span></h6>' +
        '<div class="description"><small><b>Descrição</b></small>' +
          '<ul class="list-unstyled scroll lead">' +
            '<li id="description"></li>' +
          '</ul>' +
        '</div>' +
        '<button id="id01" class="btn btn-sm btn-block btn-outline-light">Baixar</button>' +
      '</div>' +
    '</div>';

var div = document.createElement('div');
div.innerHTML = html;

2 answers

2

So far everything is correct (if your goal is to create a new element). Once you have inserted the content into the element, just use the method appendChild to add the created element to another element, thus:

const content = "Hello World";
const main = document.getElementById("main");

let element = document.createElement("div");
element.innerHTML = content;
main.appendChild(element);
<div id="main"></div>

If your goal is to add only the elements of the string without creating a new element, you can just get the main element and assign the content to it.

const content = "<div>Hello World<div>";
document.getElementById("main").innerHTML = content;
<div id="main"></div>

2


You have to catch the div then add to it the one you created with a appendchild(), as well, as you can use strings template to avoid having to use concatenation +:

let html =
  `<div class="card">
      <div class="poster"><img id="id00" src=""></div>
      <div class="details">
        <h6>Post name<br><span><a class="link" href="#" target="_blank"></a></span></h6>
        <div class="description"><small><b>Descrição</b></small>
          <ul class="list-unstyled scroll lead">
            <li id="description"></li>
          </ul>
        </div>
        <button id="id01" class="btn btn-sm btn-block btn-outline-light">Baixar</button>
      </div>
    </div>`;

let div = document.createElement('div');
div.innerHTML = html;
document.getElementById('especifica').appendChild(div);
<div id="especifica"></div>

Browser other questions tagged

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