Javascript 在两个数组[索引]选择器之间选择所有内容

Javascript 在两个数组[索引]选择器之间选择所有内容,javascript,html,css-selectors,Javascript,Html,Css Selectors,我正在用以下方式设置的网页构建在线课程: <h1>Chapter 1</h1> <p>Welcome to the chapter 1 overview.</p> <h2>Unit A</h2> <p>This is the first unit of the first chapter.</p> <h1>Chapter 2</h1> <p>This is the

我正在用以下方式设置的网页构建在线课程:

<h1>Chapter 1</h1>
<p>Welcome to the chapter 1 overview.</p>
<h2>Unit A</h2>
<p>This is the first unit of the first chapter.</p>
<h1>Chapter 2</h1>
<p>This is the chapter 2 overview</p>
第1章
欢迎阅读第1章概述

A单元 这是第一章的第一单元

第二章 这是第2章概述

为了自动化将这些网页转换为在线课程的任务,我需要做两件事:

  • 选择所有标题并确定其顺序/继承人,如下所示:
  • document.body.innerHTML=”“+document.body.innerHTML;
    MyHeaders=document.querySelectorAll(“h1、h2、h3、h4”);
    
    对于(var i=0;i假设您的所有头都具有相同的父元素(在您的示例中就是这样),此函数将起作用:

    function EVERYTHING_BETWEEN (el1, el2) {
        var siblings = Array.from(el1.parentNode.children); // get an array of all siblings
        var between =  siblings.slice(siblings.indexOf(el1) + 1, siblings.indexOf(el2)); // get the subarray of elements between
        return between.map(v => v.outerHTML).join(""); // replace each with their outerHTML and join
    }
    

    这是一个可读性最低的示例,它使用jquery,但可能可以告诉您方法。在google的帮助下,我找到了这个示例,谢谢A.Meshu。我看过nextUntil(),但它似乎不支持数组[索引]样式的选择器。例如,这应该可以工作:var elems=$('h2')。nextUntil('h2');但是,这似乎不起作用:var elems=$(MyHeaders[1]).nextUntil(我的标题[2]);