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:
xxxxxxxxxx
1
var linkElement = document.createElement('a');
2
link.href = 'https://dirask.com/';
3
link.textContent = 'Example link text...';
4
parentElement.appendChild(link);
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.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
// create link dynamically
7
var link = document.createElement('a');
8
9
// set href attribute
10
link.href = 'https://dirask.com/';
11
12
// set link text
13
link.text = 'Example link text...';
14
15
// append link element to the body
16
document.body.appendChild(link);
17
18
</script>
19
</body>
20
</html>