Create HTML Elements with JavaScript

C
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")
    .addClass("fox")
    .attr("id", "quick")
    .click(function () {
        alert("It jumped over the lazy dog!");
        console.log($(this).data());
    })
    .append($("<hr>"))
    .append(
      $("<small>").html("click for the answer"));

$("body").append(fox);
Published in: JavaScript

Looking for something? Find here!

Meet the Author

Web Geek, Tech Columnist
A
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