Ethan Marr
Ethan Marr

Reputation: 49

Is it possible to append a group of html to html page with javascript?

Im trying to make it so i can append this html below :

      <div  class="col-md-6 col-lg-5 wow bounceInUp" data-wow-duration="1.4s">
        <div class="box">
          <div class="icon"><i class="fa fa-check" style="color: #ff5100;"></i></div>
          <h4 class="title"><a href="">Title Of Box</a></h4>
          <p class="description">Description Of Box</p>
        </div>
      </div>

Im trying to append that code several times within a html page but i cant find a way, iv spent 4 hours looking this up, and found nothing :(

Upvotes: 1

Views: 981

Answers (2)

Cat
Cat

Reputation: 4226

You can use Element.prototype.insertAdjacentHTML.

Check out https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML. (Note that MDN will be down for maintenance for up to an hour later today.)

const myContainer = document.getElementById("some-element");
const myNewHtml = "<div><span>Inserted by JS</span></div>";
myContainer.insertAdjacentHTML("beforeend", myNewHtml); 
<div id="some-element">
  <span>Static content</span>
</div>

Edit
Note: A common alternative to this is to build the HTML entirely in JavaScript, using the createElement, createTextNode, and appendChild methods.
(I think the reason the this more complicated technique is common is that -- while inserting a pre-written string of HTML with insertAdjacentHTML is very convenient -- if your pre-written HTML is not written properly, you won't see any error messages until your script either fails at runtime or just inserts a nonsensical string into your page.)

Upvotes: 1

Austin T French
Austin T French

Reputation: 5131

Yes, you would need a few parts. A working easy example:

var stuff = '<div  class="col-md-6 col-lg-5 wow bounceInUp" data-wow-duration="1.4s">'+
            '<div class="box">'+
             ' <div class="icon"><i class="fa fa-check" style="color: #ff5100;"></i></div>'+
              '<h4 class="title"><a href="">Title Of Box</a></h4>'+
              '<p class="description">Description Of Box</p>'+
            '</div>'+
          '</div>'
          
    var add = function(){
  
      document.getElementById('container').innerHTML += stuff;
    }
<div id="container"></div>
<button type="button" onclick="add()">add </button>

Assuming vanilla Js above:

But the variable stuff is a string.

On some event, in this case a button click we get that string and append the dom element with that string.

I used a element Id as the selector, but you could also use a class, an event to get a parent or sibling element etc..

Then you use innerHtml to append (or replace if you wanted) the string into the DOM.

Upvotes: 2

Related Questions