Skip to content
Advertisement

Target classes inner HTML based on URL parameters

I asked a similar question about customizing the inner HTML of span id’s, and although it worked perfectly, I’m looking for a solution that will let me use multiple instances of the same target on the same page (doesn’t work with id’s since they need to be unique).

Right now, I am targeting elements with something like <span id="organization">placeholder</span> but I want to be able to use the same “organization” placeholder in multiple spots.

This is the current script:

const queryString = window.location.search;

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

for (const parameter of parameters) {
    document.getElementById(parameter[0]).innerHTML = parameter[1];
}

I’ve tried targeting the classes instead by both name (getElementsByName) and class (getElementsByClassName) but am having trouble keeping the above script working with dynamic URL parameters.

Thank you for any help.

Advertisement

Answer

You can bind by getElementsByClassName, but you need to convert from HTMLCollection to an array by spread operator, also you can use forEach to loop throw each element and set the innerHTML.

Here if you set for example

?one=1&two=2

There element whose class="one" should be fill with 1 and same for two

html:

<div class="one"></div>
<div class="one"></div>
<div class="two"></div>

js:

const queryString = window.location.search;

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

for (const parameter of parameters) {
    [...document.getElementsByClassName(parameter[0])].forEach(element => element.innerHTML = parameter[1]);
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement