简体   繁体   中英

How do I add link to an element with JavaScript?

So instead of directly using tag in each element, is there a way to add the tag dynamically?

What I'm trying to do is that first I have a calendar, and when a user clicks a particular date on the calendar, the user can see what happened in that date at a separate page.
The thing is that I'm using django-scheduler library, so the calendar is pre-desiged, meaning I cannot directly make changes to the code. All I have in my template is {% calendar %} . So I figured I'd have to control using JavaScript.

Here's what I see in the 'source' of the page:

...
<div class="content" data-date="2020-05-27"></div>
<div class="content" data-date="2020-05-28"></div>
<div class="content" data-date="2020-05-29"></div>
...

For each data-date , I want to add link which looks like: www.some-webpage.com/2020-05-27

Is it ever possible to do this with JavaScript? Thanks in advance. :)

You can add the function below in the onClick of the button. Here I am using document.querySelectorAll to select all elements with data-date attribute and then looping over each element to form an a tag with link based on the data-date attribute.

 function addDateLink() { document.querySelectorAll('[data-date]').forEach(div => { const date = div.getAttribute('data-date') div.innerHTML = `<a href="www.some-webpage.com/${date}">${date}</a>` }) }
 <div class="content" data-date="2020-05-27"></div> <div class="content" data-date="2020-05-28"></div> <div class="content" data-date="2020-05-29"></div> <input type="button" value="Display Link" onclick="addDateLink()"/>

you can use map-function for every and add a link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM