Create HTML Elements with 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);
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory