# Generating HTML in Javascript

There are many ways to generate HTML in Javascript. I will discuss two out of it.

1. Using `createElement() method`
    
2. Using `insertAdjacentHTML method`
    
    **1\. creating elements and append it**
    

In this method an HTML element is created by using `createElement()` method and then that created element is appended. Let's consider the example.

```xml
<!DOCTYPE html>
 <html lang="en">
 <head>
   <meta charset="UT-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
 </head>
 <body>
   
         
 </body>
 </html>
```

Now if we want to create an html element e.g(div) and to give that html element a class name or Id and to give element inner content. That can be done in Javascript using `createElement() and appendChild()` methods.

```javascript
const div = document.createElement("div");                 div.className="example";              div.id = "to-do";          div.innerHTML= "<h1> JavaScript</h1>";          document.body.appendChild(div);
```

Above JavaScript code generate the following html.

```xml
 <!DOCTYPE html>
 <html lang="en">
 <head>
   <meta charset="UT-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
 </head>
 <body>
   <div class="example" id="to-do">          <h1> JavaScript </h1>   </div>
         
 </body>
 </html>
```

**2\. Using insertAdjacentHTML() method**

In this method html element will be generated with respect to other html element.

`insertAdjacentHTML("position", "html")`

Position string would be one out of these four:

1. beforebegin
    
2. afterbegin
    
3. beforeend
    
4. afterend
    

Other argument of this method would be string containg html element to be created.

Let's take an example.

```xml
<body>                <h1 id = "top-text">  JavaScript          </h1>             </body>
```

If we want to insert a paragraph element after the h1 element, then this mathod will come into play. Moreover the position of new element can also be adjusted easily using parameters beforebegin, afterbegin, beforeend and afterend.

```javascript
const text= document.querySelector("#top-text");                     text.insertAdjacentHTML("afterend","<p> JavaScript is one of most popular language. </p>");
```

Above JavaScript code will generate the following html.

```xml
<body>                <h1 id = "top-text"> JavaScript</h1>       <p> JavaScript is one of most popular language. </p>               </body>
```

That's all about it. Hope you will find it helpful?
