Home > Software design >  How to fill part of a link after the slash with a value from an array
How to fill part of a link after the slash with a value from an array

Time:06-18

I want to create a "dynamic" link in a page that changes according to a value from an array. Sort of a f-string in Python…

So I have this variable with an array:

let movies = [
    {
        "originalTitle": "The Shawshank Redemption",
        "director": "Frank Darabont",
        "year": 1994,
        "genre": "Drama",
        "runtimeMinutes": 142,
        "averageRating": 9.3
      },
      {
        "originalTitle": "The Godfather",
        "director": "Francis Ford Coppola",
        "year": 1972,
        "genre": "Crime",
        "runtimeMinutes": 175,
        "averageRating": 9.2
      }
]

And I want in my HTML to "fill" the URL with the title of the movie. Changing this part domain.com/search?q=The Godfather where the "The Godfather" section could be another movie, like domain.com/search?q=The Shawshank Redemption

<p><a href="domain.com/search?q=The Godfather">Click here</a> to search where you can watch this movie.</p>

Keep in mind that I have a variable that selects which movie will be inserted already. I just need to know how to make this "dynamic" anchor tag and insert the movie inside that variable.

I know how to do this with .textContent with span tags in my HTML. But what I want to replace is inside the anchor tag. How can I achieve this?

CodePudding user response:

You can get the anchor element with querySelector and then set the href attribute, try this:

let movies = [
    {
        "originalTitle": "The Shawshank Redemption",
        "director": "Frank Darabont",
        "year": 1994,
        "genre": "Drama",
        "runtimeMinutes": 142,
        "averageRating": 9.3
      },
      {
        "originalTitle": "The Godfather",
        "director": "Francis Ford Coppola",
        "year": 1972,
        "genre": "Crime",
        "runtimeMinutes": 175,
        "averageRating": 9.2
      }
];

let anchor = document.querySelector('#anchor');
anchor.href = `domain.com/${movies[0].originalTitle}`;
<a id="anchor">Click</a>

CodePudding user response:

You can use URLSearchParams API

const movies = [{
    "originalTitle": "The Shawshank Redemption",
    "director": "Frank Darabont",
    "year": 1994,
    "genre": "Drama",
    "runtimeMinutes": 142,
    "averageRating": 9.3
  },
  {
    "originalTitle": "The Godfather",
    "director": "Francis Ford Coppola",
    "year": 1972,
    "genre": "Crime",
    "runtimeMinutes": 175,
    "averageRating": 9.2
  }
];

const anchor = document.querySelector('#anchor');
const searchParams = new URLSearchParams(window.location.search);
searchParams.set("?q", movies[0].originalTitle);
anchor.href  = searchParams.toString();

console.log(anchor.href)
<p><a id="anchor" href="https://domaintest.com/">Click here</a> to search where you can watch this movie.</p>

  • Related