+ 5

Create element in JavaScript - html dom

How can I create element for link like ... <a href="mylink.com/?param=*point_variable*"> abc </a> For example, if we wanna create element for button, then we write like this... var btn = document.createElement("Button"); Similarly, I wanna create a link like this in JavaScript. So, what should I do???

21st Mar 2021, 4:16 AM
axita
axita - avatar
3 ответов
+ 4
Something like this would work: var link = document.createElement("a"); link.setAttribute('href', 'mylink.com/?param=*point_variable*'); link.innerText = 'abc'; You probably want to replace '*point_variable*' but you can likely figure out how to format your URL and get that part from your variable. You may want to use encodeURIComponent if your variable may have some special characters that you want escaped.
21st Mar 2021, 4:19 AM
Josh Greig
Josh Greig - avatar
+ 3
Thank you 🤗
21st Mar 2021, 5:46 AM
axita
axita - avatar
+ 1
obviously, you need to append the newly created element somewhere in your html document (through DOM)... document or element appendChild() method is a way returning the newly inserted element, while append() method could append any number of element, while returning nothing ;)
23rd Mar 2021, 10:53 PM
visph
visph - avatar