How do I switch a list through another list?

  • 0
    and so, there are 10 buttons, 10 different lists (1 button 1 list), how can you make 1 list appear when you click on button 1, when you click on button 2, the 2nd list appears and the first one is deleted, I tried it through toggle, but it's not quite right
    JavaScript Anonymous, Mar 1, 2020

  • 2 Answers
  • 0
    The easiest way. We wrap everything in a div and put a wiretap on it. If the click is not on the button, exit the function. We set the date attributes for buttons and lists. By clicking on the button, we check if the list related to it is open. If it is open, close it and exit the function. If it is closed, we check if there are any open lists, if there are, we close it. Open the list for the button. I placed the lists next to the buttons only to show that the necessary ones are opening and closing. The markup can be done as required, the main thing is that the buttons and lists match the date attributes and are inside the root element. If you need to move buttons to other parts of the document, you can correct the search for elements to search the entire document. In the latter option, if there may be several such blocks on the page, you can add additional date attributes or prefixes to the existing ones.



    - const lists = new Array(10)
    - const items = new Array(3)

    each i, idx in lists
    ) open #{idx + 1}
    each i, idx in items
    li list elem #{idx + 1}


    display: none
    display: block


    const rootClass = 'lists-app'
    const openClass = 'lists-app__list--open'
    const $listsRoot = document.querySelector(`.${rootClass}`)

    const findList = idx => {
    return $listsRoot.querySelector(`[data-list='${idx}']`)
    const closeList = $el => {
    const openList = $el => {
    const isOpen = $el => $el.classList.contains(openClass)
    const getOpenList = () => {
    return $listsRoot.querySelector(`.${openClass}`)

    $listsRoot.addEventListener('click', e => {
    if (!'data-list-toggle')) {

    const idx =
    const $list = findList(idx)

    if (isOpen($list)) {

    const $openList = getOpenList()
    $openList ? closeList($openList) : null


    Cole Schmidt

  • 0
    For example It is called "dependent lists"

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!