Categories
JavaScript Answers jQuery

What is the Best Way to Add DOM Elements with jQuery?

Spread the love

To add DOM elements with jQuery, we can use the jQuery appendTo method.

For instance, if we want to add an anchor element to the body element, we write:

$("<a/>", {
  id: 'link',
  href: 'http://www.example.com/',
  text: 'Example Page'
}).appendTo("body");

We call $ with '<a/>' to create a new element.

The 2nd argument we passed into $ are the attributes and the values of the element.

Then we call appendTo on the returned object with 'body' to attach the element to body.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *