Skip to content

USWDS - Enhancement: Combo Box list HTML is rebuilt every time the list is displayed #6193

@mahoneycm

Description

@mahoneycm

Describe the bug

Every time the combo box list is opened, the JS rebuilds every li element within the unordered list whether there has been a change to the results or not.

Steps to reproduce the bug

  1. Go to Combo Box
  2. Inspect HTML - At the start you see an empty ul element
  3. Open the combo box drop down
  4. li elements are appended to the DOM
  5. While viewing the li elements in the devTools window, close and reopen the combo box
  6. li elements flash because they are removed and re-appended to the DOM

Expected Behavior

li elements should only be removed and added to the DOM when there is a change to the list or required attributes.

Related code

Code that builds the options HTML:

const optionHtml = options.map((option, index) => {
const optionId = `${listOptionBaseId}${index}`;
const classes = [LIST_OPTION_CLASS];
let tabindex = "-1";
let ariaSelected = "false";
if (optionId === selectedItemId) {
classes.push(LIST_OPTION_SELECTED_CLASS, LIST_OPTION_FOCUSED_CLASS);
tabindex = "0";
ariaSelected = "true";
}
if (!selectedItemId && index === 0) {
classes.push(LIST_OPTION_FOCUSED_CLASS);
tabindex = "0";
}
const li = document.createElement("li");
li.setAttribute("aria-setsize", options.length);
li.setAttribute("aria-posinset", index + 1);
li.setAttribute("aria-selected", ariaSelected);
li.setAttribute("id", optionId);
li.setAttribute("class", classes.join(" "));
li.setAttribute("tabindex", tabindex);
li.setAttribute("role", "option");
li.setAttribute("data-value", option.value);
li.textContent = option.text;
return li;
});

Code that determines when to append the HTML:

if (numOptions) {
listEl.innerHTML = "";
optionHtml.forEach((item) =>
listEl.insertAdjacentElement("beforeend", item),
);
} else {
listEl.innerHTML = "";
listEl.insertAdjacentElement("beforeend", noResults);
}

Screenshots

Recording of this behavior:

Kapture.2024-11-08.at.15.26.38.webm

System setup

  • USWDS Version: 3.9.0
  • Operating System: MacOS Sonoma 14.6.1
  • Browser: Arc (chromium)

Additional context

No response

Code of Conduct

Metadata

Metadata

Assignees

Labels

Projects

Status

Backlog

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions