EN
JavaScript - create link element dynamically
0
points
In this article, we would like to show you how to create a link element dynamically using JavaScript.
Quick solution:
var linkElement = document.createElement('a');
link.href = 'https://dirask.com/';
link.textContent = 'Example link text...';
parentElement.appendChild(link);
Practical example
In this example, we create link (a) element using createElement() method. Then after specifying its attributes such as href and text, we append the link to the body element.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<script>
// create link dynamically
var link = document.createElement('a');
// set href attribute
link.href = 'https://dirask.com/';
// set link text
link.text = 'Example link text...';
// append link element to the body
document.body.appendChild(link);
</script>
</body>
</html>