Ryan Oh
Ryan Oh

Reputation: 657

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. :)

Upvotes: 0

Views: 103

Answers (2)

Ashish
Ashish

Reputation: 4330

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()"/>

Upvotes: 2

Mazur Ekaterina
Mazur Ekaterina

Reputation: 56

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

Upvotes: 0

Related Questions