Dynamically generate an anchor tag with JavaScript/jQuery
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
1 2 3 4 5 6 7 8 9 10 |
document.getElementById('generate').onclick = function() { var a = document.createElement('a'); a.target = '_blank'; a.href = 'https://www.techiedelight.com/'; a.innerText = 'Techie Delight'; var container = document.getElementById('container'); container.appendChild(a); container.appendChild(document.createElement('br')); } |
HTML
1 2 3 4 5 6 7 8 9 |
<!doctype html> <html lang="en"> <body> <div id="container"></div> <div> <button id="generate">Generate Hyperlink</button> </div> </body> </html> |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$(document).ready(function() { $('#generate').click(function() { $('#container').append( $(document.createElement('a')).prop({ target: '_blank', href: 'https://www.techiedelight.com/', innerText: 'Techie Delight' }) ).append( $(document.createElement('br')) ); }) }); |
HTML
1 2 3 4 5 6 7 8 9 |
<!doctype html> <html lang="en"> <body> <div id="container"></div> <div> <button id="generate">Generate Hyperlink</button> </div> </body> </html> |
Alternatively, here’s a shorter version:
JS
1 2 3 4 5 6 7 |
$(document).ready(function() { $('#generate').click(function() { var url = 'https://www.techiedelight.com/'; var text = 'Techie Delight'; $("#container").append(`<a href="${url}" target="_blank">{text}</a>`); }) }); |
HTML
1 2 3 4 5 6 7 8 9 |
<!doctype html> <html lang="en"> <body> <div id="container"></div> <div> <button id="generate">Generate Hyperlink</button> </div> </body> </html> |
That’s all about dynamically generate an anchor tag in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)