Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add anchor tags dynamically to a div in Javascript?

Tags:

javascript

How to add a list of hyperlinks (with their events and properties) dynamically to a div in Javascript?

like image 248
Ahmad Farid Avatar asked Apr 01 '11 23:04

Ahmad Farid


People also ask

How do I link an anchor tag to a div?

As long as your anchor has an ID you can link to a location in your view by clicking the div you will just need some javascript. Setting the window. location. hash value will put the focus of the view on the selected ID.

Can we use anchor tag in JavaScript?

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.

How do you add a dynamic tag in HTML?

With document. createElement() method you can create a specified HTML element dynamically in JavaScript. After creation you can add attributes. If you want the element to show up in your document, you have to insert in into the DOM-tree of the document.


1 Answers

here's a pure Javascript alternative:

var mydiv = document.getElementById("myDiv"); var aTag = document.createElement('a'); aTag.setAttribute('href',"yourlink.htm"); aTag.innerText = "link text"; mydiv.appendChild(aTag); 
like image 150
danniel Avatar answered Sep 19 '22 00:09

danniel