Automatically close all the other
tags after opening a specific
tag

前端 未结 6 518
日久生厌
日久生厌 2021-02-06 01:08

Here is my code.



        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-06 01:09

    Another approach, slightly shorter, slightly more efficient, without dependencies, and without onclick attributes in the HTML.

    // Fetch all the details element.
    const details = document.querySelectorAll("details");
    
    // Add the onclick listeners.
    details.forEach((targetDetail) => {
      targetDetail.addEventListener("click", () => {
        // Close all the details that are not targetDetail.
        details.forEach((detail) => {
          if (detail !== targetDetail) {
            detail.removeAttribute("open");
          }
        });
      });
    });
    1Demo 1
    2Demo 2
    3Demo 3

提交回复
热议问题