Adding sp-menu items via API

I’m trying to add menu items to a sp-menu component from Javascript but I’m not sure how to go about this. Do spectrum web components need to be imported from my script file? I keep getting the error cannot import outside module error. If I try to do a “new MenuItem()” that isn’t recognized. I have an empty menu element in HTML:


And I want to populate layer names when the user clicks on a button using script. Any help is appreciated.

You can treat sp-menu-items like any other HTML tag from JS. Meaning that to add them dynamically, you can use appendChild on the parent container.

const layers = ["Layer 1", "Layer 2"];
const menu = document.querySelector("#menu");
layers.forEach(text => {
    const item = document.createElement("sp-menu-item");
    item.textContent = text;
    menu.appendChild(item);
});

Ah, I see. That’s very convenient. Thank you so much for the prompt response!