如何将 JS 应用于(打开的)手风琴,当它在 DOM 加载时关闭

How to apply JS to an (openned) accordion, when it is closed on DOM load

https://www.apis.de/dienstleistungen/trainings/ 我有几个手风琴。其中有包含日期​​和其他信息的表格。每个都有一个在服务器端生成的 ID (php)。我想简单地使用选择器路径(开发工具)获取 tbody 标签 --> 获取子节点并切换,例如node[11] 和 node[12] 左右。问题是我写的 JS 函数没有被识别,因为手风琴在页面加载时关闭并且不识别选择器路径(使用 IIFE)

(function(){
let first_table = document.querySelector("#site-wrapper > div > div > main > article > section > ul > li.is-expanded > ul > li > table > tbody"); // gets the tbody of first accordion (Schulungen Deutschland)
console.log(first_table); // returns null, because the accordion was not open when the function is executed. 

})();


编辑:我之前写的不正确。

不使用查询选择器,您可以使用 document.getElementsByTagName('tbody')[0]

访问第一个 tbody

如果您能够在客户端访问要交换的元素的 ID,则可以使用 jfriend00 写道的代码交换它们:

function doSwap() {
    swapElements(document.getElementById("one"), document.getElementById("two"));
}

function swapElements(obj1, obj2) {
    // create marker element and insert it where obj1 is
    var temp = document.createElement("div");
    obj1.parentNode.insertBefore(temp, obj1);

    // move obj1 to right before obj2
    obj2.parentNode.insertBefore(obj1, obj2);

    // move obj2 to right before where obj1 used to be
    temp.parentNode.insertBefore(obj2, temp);

    // remove temporary marker node
    temp.parentNode.removeChild(temp);
}
<button onclick="doSwap()">Swap</button><br><br>

<ul>
    <li id="one">Item A</li>
    <li id="two">Item B</li>
    <li>Item C</li>
</ul>

  1. 选择器路径为假
  2. 在您要观看的 "li" 元素上放置一个点击事件,因为最初 "is-expanded" class 在页面加载时对 DOM 不可用。
  3. ".querySelectorAll" 不是 "querySelector"

           let accordianSection = document.querySelectorAll("#site-wrapper > div > div > main > article > section > ul.accordion ")[0];
           accordianSection.addEventListener( "click", function(){
    
           let selectedTbody = document.querySelectorAll("#site-wrapper > div > div > main > article > section > ul > li.is-expanded > ul > li > table > tbody ")[0];
    
             console.log(selectedTbody);
    
            });