在特定元素之前隐藏所有元素

tot*_*oob 18 javascript

使用jQuery并在每个h1内的内容周围有一个包装容器,我可以很容易地隐藏它们.

但没有包装容器,怎么会这样呢?

什么是在下一个h1之前做一些隐藏所有事情的最佳方法?

我没有使用jQuery,因为这是React应用程序的一部分.

h1 {
  border-bottom: solid 1px #000;
}

span {
  float: right;
}
Run Code Online (Sandbox Code Playgroud)
<h1>h1 <span>x</span></h1>
<p>test 1</p>
<h2>h2</h2>
<p>test 2</p>

<h1>h1-1 <span>x</span></h1>
<p>test 3</p>
<h2>h2-2</h2>
<p>test 4</p>
Run Code Online (Sandbox Code Playgroud)

或者在div标签中的下一个h1之后和之前包装所有内容?

Pab*_*123 2

听起来你想要类似 jQuerynextUntil()功能的东西。这是在 vanilla js 中执行此操作的一个很好的指南。代码最终看起来像这样:

var nextUntil = function (elem, selector, filter) {

    // Setup siblings array
    var siblings = [];

    // Get the next sibling element
    elem = elem.nextElementSibling;

    // As long as a sibling exists
    while (elem) {

        // If we've reached our match, bail
        if (elem.matches(selector)) break;

        // If filtering by a selector, check if the sibling matches
        if (filter && !elem.matches(filter)) {
            elem = elem.nextElementSibling;
            continue;
        }

        // Otherwise, push it to the siblings array
        siblings.push(elem);

        // Get the next sibling element
        elem = elem.nextElementSibling;

    }

    return siblings;

};
Run Code Online (Sandbox Code Playgroud)

我显然不知道你正在做的事情背后的上下文,但我认为通过更改 HTML 有更好的方法。这甚至可以让你只用css nth 子选择器来做一些事情