Refactor function to work with arrays


I have this script, which rearranges DOM elements on a site in response to changing resolution basically creating a mobile version with different order of elements.

// repositionHighwaySelectorForMobile

const highwaySection = document.querySelector(".highway");
const highwayTitle = document.querySelector(".highway__title");
const highwayPicSelector = document.querySelector(
const mobileTitleAndSelectorWrapper = document.createElement("div");
const highwayMobileLine = document.querySelector(".highway__mobile-line");
const highwayArrowLeftContainer = document.querySelector(
const highwayArrowRightContainer = document.querySelector(

function repositionHighwaySelectorForMobile() {
  if (breakPoint.matches) {
    mobileTitleAndSelectorWrapper.appendChild(highwayPicSelector); = "flex"; = "row"; = "space-between"; = "center"; = "5px"; = "24px"; = "24px"; = "24px"; = "24px";
  } else { = "50px"; = "50px"; = "50px"; = "50px";





breakPoint.addEventListener("change", () =>

It works just fine, but later in my work I’ve found out that that exact section will be present in three instances with slightly different content, acting as slides to be horizontally scrolled.

I’ve created the slides by copypasting this section three times and now I have to teach this function to reposition the elements on each page as it does for the first. I understand that all variables are arrays with three elements now.

Is there an elegant way to do so? Or I have to rewrite each manipulation inside function to work with arrays?

What is changing each time? Pass that as a parameter to your function.

@kevinSmith divs which represent slides and thier internals are changing.

In this case this function could look like this


but it doesn’t work since the variables are declared earlier and they grab only the first ones from arrays of ones which are in inside the slide divs.

It’s hard to visualize what you mean without working on your code. But if you need a different DOM selector, pass that in. Or pass in the information it needs to find the section of the DOM that it wants.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.