DEV Community

loading...
Cover image for How to create an HTML generator with JavaScript?

How to create an HTML generator with JavaScript?

murtuza
Author at CSS-Tricks. A Front-end Enthusiast, a programmer, a problem solver and a human being who tries to keep a good relationship with bugs!
Updated on ・3 min read

Before you proceed: This post is not about creating a safe or the best HTML generator rather it's just something for fun that you can try by using template literals in JavaScript. It was a fun experiment for me.

Ever tired of writing multiple lines of similar HTML? If you are, then you can automate the process by using template literals in JavaScript. Let's see how we can do that.

Let's say you have multiple boxes which are actually hyperlinks and you want to create multiple of them.

HTML Hyperlinks

One way is to just copy and paste the HTML code and make changes to a particular section of the code. This approach can work for small projects but if your project is big enough, then it can become a mess.

Alternatively, you can create your own HTML generator using template literals in JavaScript which will generate HTML code for you!

Template Literals in JavaScript

Template literals in JavaScript are nothing but string literals which allow you to embed various expressions into the string. They are enclosed in backticks. For embedding an expression the syntax goes like this,

let string = `first part of the string ${expression} second part of the string`;
Enter fullscreen mode Exit fullscreen mode

Now, let's create the HTML generator.

Create respective input fields for link URL, Title & a Tag. You can add your own input fields also if you want to.

<div id="contains">
      <label for="title" class="title">Title</label>
      <input type="text" id="title" name="title">
      <label for="url" class="url">URL</label>
      <input type="url" id="url" name="url">
      <label for="tag" class="tag">Tag</label>
      <input type="text" id="tag" name="tag">
      <button id="submit">Generate</button>
</div>
Enter fullscreen mode Exit fullscreen mode

Next, create a textarea field in which the resultant code will be displayed as well as create a button to copy the code to the clipboard.

<div class="result">
      <textarea class="result_text" type="text" rows="5"></textarea>
      <button class="copy_btn"><i class="fas fa-clipboard"></i></button>
</div>
Enter fullscreen mode Exit fullscreen mode

HTML Generator User Interface

JavaScript

We will create a function named generate(). This function has three parameters — title, url and tag. It will take in the value of the title, the url, and the tag that we have input in the field as arguments.

function generate(title, url, tag){
   //code
}
Enter fullscreen mode Exit fullscreen mode

Further, we will use template literals and we will embed the title, the url & the tag into the string. Then, set the value of the result field to the string that is generated.

let title = document.querySelector("#title");
let url = document.querySelector("#url");
let tag = document.querySelector("#tag");
let result = document.querySelector(".result_text");

function generate(title, url, tag){
    let final_string = `<a href="${url}"><div class="link"><div class="banner">${tag}</div>${title}</div></a>`;
    result.value = final_string;
}
Enter fullscreen mode Exit fullscreen mode

All of this will take place after the user clicks the generate button and so let's add an eventListener to it.

let submit_btn = document.querySelector("#submit");
submit_btn.addEventListener("click", () => {
    generate(title.value, url.value, tag.value);
    title.value = "";
    url.value = "";
    tag.value = "";
});
Enter fullscreen mode Exit fullscreen mode

In order to copy the code from the textarea, we can define a function called copy() and then call the function when the user clicks on the 'copy to clipboard' button.

let copy_btn = document.querySelector(".copy_btn");
copy_btn.addEventListener("click", () => {
    copy();
})
function copy(){
    result.select();
    document.execCommand("copy");
}
Enter fullscreen mode Exit fullscreen mode

Here's a quick demo:

Now, you can copy the code into your main project.
This is just one of the use cases of template literals. You can do a lot of thins by using template literals in JavaScript. They make your life as a JavaScript developer easy.

Signing off.

Discussion (10)

Collapse
lukeshiru profile image
LUKESHIRU

Interesting approach, but I believe that is safer to actually create the html elements in memory, so the user doesn't have a way of putting custom HTML in the attributes, and you also reduce the chances of having badly formatted html (missing closing tags and stuff like that). With this approach the code for generate could look something like this:

/**
 * Create a new element with given tag and given properties set.
 *
 * @template {keyof HTMLElementTagNameMap} Tag
 * @param {Tag} tag
 */
const createElement =
    tag =>
    /**
     * @param {Partial<HTMLElementTagNameMap[Tag]>} properties
     * @returns {HTMLElementTagNameMap[Tag]}
     */
    properties =>
        Object.assign(
            document.createElement(tag),
            properties
        );

/**
 * Uses `createElement` setting `div` as the tag.
 */
const createDiv = createElement("div");

/**
 * Generate the template HTML.
 *
 * @param {string} title
 * @param {string} href
 * @param {string} tag
 */
const generate = (title, href, tag) => {
    const anchor = createElement("a")({ href });
    const linkDiv = createDiv({ className: "link" });

    linkDiv.appendChild(
        createDiv({ className: "banner", textContent: tag })
    );
    linkDiv.appendChild(document.createTextNode(title));
    anchor.appendChild(linkDiv);

    return anchor.innerHTML;
};
Enter fullscreen mode Exit fullscreen mode

Because with this new code, generate doesn't change the content of the textarea by itself but actually returns the html, we need to change the usage a little as well:

document.querySelector("#submit").addEventListener("click", () => {
    // We change this line only:
    result.value = generate(title.value, url.value, tag.value);
    title.value = "";
    url.value = "";
    tag.value = "";
});
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
fjones profile image
FJones

For user-facing code, I would absolutely agree that handling DocumentFragments is the safer (and sometimes more useful) option.

However, producing raw HTML is excellent for things like email template generation. With HTML emails, you're always working with a lot of constraints due to the wildly varying support in client capabilities. A lot of the HTML you end up generating is in fact invalid by any modern spec. Opinionated templating frameworks are often less-than-useful here, and even more often just too big for the intended purpose. Rolling your own is, imo, an excellent way to solve that.

Collapse
murtuzaalisurti profile image
murtuza Author

Honestly speaking, I didn't know much about templating HTML prior to this blog post but now I know! Thanks! I will keep exploring!

Collapse
murtuzaalisurti profile image
murtuza Author

I agree! This was just me experimenting with template literals. But today I learnt something new! Thanks!

Collapse
r4nd3l profile image
Matt Miller

That was interesting! I would like to so more of this, if there are any new updates or so. cheers

Collapse
murtuzaalisurti profile image
murtuza Author

Cool! More tutorials like this coming soon!

Collapse
tohagan profile image
Tony OHagan

So why are we reinventing web components, VueJS, React, Angular?

Collapse
murtuzaalisurti profile image
murtuza Author

To learn how they work!

Collapse
jagadishbabusaka profile image
jagadishbabusaka

Creating html generator in javascript is challenging but very interesting to write the code. Here i created an html generator using angularjs htmlcodegenerator-tools.com

Collapse
pankaj_chetry12 profile image
Pankaj Chetry

I created a blog using codes. Hexxdroid