Create HTML Elements with JavaScript

Published in: JavaScript

You can create HTML elements directly with JavaScript /jQuery and also assign data attributes, CSS style, click handlers, classes and IDs to these elements through chaining.

Here’s an example.

var fox = $("<div>")
    .css("background", "lightyellow")
    .css("padding", "15px")
    .html("What did the fox do?")
    .data("color", "brown")
    .attr("id", "quick")
    .click(function () {
        alert("It jumped over the lazy dog!");
      $("<small>").html("click for the answer"));

Published in: JavaScript

Looking for something? Find here!

Meet the Author

Web Geek, Tech Columnist
Amit Agarwal

Amit Agarwal is a Google Developer Expert in GSuite and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. Read more on Lifehacker and YourStory

Get in touch