This post will discuss how to dynamically generate an anchor tag in JavaScript and jQuery.

1. Using JavaScript

In vanilla JavaScript, you can use the document.createElement() method, which programmatically creates the specified HTML element. The following example creates a new anchor tag with desired attributes and appends it to a div element using the Node.appendChild() method.

JS


HTML



Edit in JSFiddle

2. Using jQuery

With jQuery, you can use the .append() method to append the anchor tag at the end of the specified div element. This is demonstrated below:

JS


HTML



Edit in JSFiddle

 
Alternatively, here’s a shorter version:

JS


HTML



Edit in JSFiddle

That’s all about dynamically generate an anchor tag in JavaScript and jQuery.