Cs238975
Cs238975

Reputation: 31

How to insert dynamic URL parameters in HTML (Javascript)

I'm working on a marketing landing page that would take parameters in a URL and then display them in the HTML of an id on the page. Right now, I have every text placeholder defined in addition to each parameter from the URL.

The code below is working fine, but is there a way to remove the redundancies so that if any id matches the name of a parameter in the URL (e.g. a span has id "city" is automatically matched with the parameter "city"), they recognize and update the inner HTML? Thanks for any help.

const queryString = window.location.search;

const urlParams = new URLSearchParams(queryString);

const company_text = document.getElementById("company");
const company = urlParams.get('company');
if (company != null){
    company_text.innerHTML = company;
}

const city_text = document.getElementById("city");
const city = urlParams.get('city');
if (city != null){
    city_text.innerHTML = city;
}

Edited to update parameter names for clarity

Upvotes: 0

Views: 1871

Answers (2)

Caeden
Caeden

Reputation: 416

This can be done by iterating over a list of all URL parameters and changing the HTML content of elements with the correct IDs.

var parameters = new URLSearchParams(window.location.search);

for (const parameter of parameters) {
  document.querySelectorAll(`[id=${parameter[0]}]`).forEach(element => {
    element.innerHTML = parameter[1];
  });
}

I hope this solves your problem.

Best Regards,

Upvotes: 0

Johnny5
Johnny5

Reputation: 6862

You could put something like this at the end of your page

for(const [id, val] of urlParams.entries()) {
    const htmlElement = document.getElementById(id);
    if(htmlElement) {
        htmlElement.innerHTML = val;
    }
}

Keep in mind that the same parameter can appear more than one time in the query string (e.g. ?x=1&x=2). In that case there will be two entries with the same id.

Ref for entries.

Upvotes: 1

Related Questions