0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

entries() returns the iterator and is equivalent to iterate the object itself. It could have been omited here. As for forEach method, it's just a different way to iterate on the values. I prefer for of construct but I guess it's a matter of opinion.
0

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,

4 Comments

This worked perfectly. Wish I could buy you a coffee (if there's a way, let me know). Thank you!
No problem. Glad I could be of assistance!
Realized this isn't working for pages where the ID is being used more than once (it's updating only the first instance). Is there a way to have it apply to all instances? Thinking we'd need to change to use a target other than an ID...
I edited the code to work with multiple elements of the same ID. The algorithm iterates over the URL search parameters and then iterates over and modifies each element with a particular ID.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.