Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.getElementById(parameter[0]).innerHTML = parameter[1];
}

I hope this solves your problem.

Best Regards,

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading