使用CSS / JS定位特定元素之后的元素

时间:2016-10-21 20:12:06

标签: javascript jquery html css

使用Javascript / jQuery或CSS选择器,我如何定位特定元素之后的元素?要明确的是,我并不是指在(邻近)之后,我指的是页面下方存在的任何和所有匹配元素。

想象一组<p> s:

<p>Lorem</p>
<p id="special">Ipsum</p>
<p>Dolor</p>
<p>Sit</p>
<p>Amet</p>

现在我想定位<p>之后的所有p#special ...所以内容为“Dolor”,“Sit”和“Amet”的那些$('p#special::allAfter p').each(... 。我希望有一些选择器可用,如:

Firebase.database().ref('userData').once('value').then((data) => {

    // --- USER ID VALIDATION ---//
    if (!userIds[USER_ID]) {
      throw(`Invalid User ID: ${USER_ID}`);
    }
    updates[`${USER_ID}/sessions/${newSessionKey}`] = event.session;

    // --- UPDATE DATABASE ---//
    Firebase.database().ref().update(updates)
      .then(() => context.succeed('Database Write Successful.'))
      .catch(error => context.fail(`Database Write Error: ${error}`));
})
.catch(error => context.fail(`Database Access Error: ${error}`));

我该怎么做?

5 个答案:

答案 0 :(得分:3)

您可以使用CSS中的general sibling选择器

  

〜组合器分离两个选择器并匹配第二个选择器   元素只有在第一个元素之前,并且两者共享一个共同元素   父节点。

#special ~ p {color: red}
<p>Lorem</p>
<p id="special">Ipsum</p>
<p>Dolor</p>
<p>Sit</p>
<p>Amet</p>

在jQuery中,它被称为"Next Siblings Selector "

$('#special ~ p')

答案 1 :(得分:2)

nextAll()是您正在寻找的jQuery函数。

请参阅此文档:https://api.jquery.com/nextAll/

答案 2 :(得分:0)

的jQuery

next()https://api.jquery.com/next/

nextall()https://api.jquery.com/nextAll/

nextuntil()https://api.jquery.com/nextUntil/(可能更有用)

$(&#34; p#special&#34;)。next()。css(&#34; background-color&#34;,&#34; red&#34;);

答案 3 :(得分:0)

如果所有元素都在同一个父元素中,则可以使用General Sibling Combinator ~

#special ~ p {
  color: red;
}
<p>Lorem</p>
<p id="special">Ipsum</p>
<p>Dolor</p>
<p>Sit</p>
<p>Amet</p>

然而,<p>必须是兄弟

否则,如果你想在页面中选择每一个p,无论它是否是兄弟,你都必须使用JS:

var para = document.querySelectorAll("p"), //Get p's
  addColor = false;

Array.prototype.forEach.call(para, function(p) {
  //Loop through paragraphs

  //If addColor is true, add color to paragraph
  if (addColor) p.style.color = "red";

  //If the current paragraphs id is special, set addColor to true
  if (p.id == "special") addColor = true;
});
<div>
  <p>Test</p>
  <p>Test</p>
  <p id="special">Test</p>
</div>
<p>Test</p>
<p>Test</p>
<div>
  <div>
    <p>Test</p>
  </div>
</div>

或者,在jQuery中:

var para = $("p"),
  addColor = false;

para.each(function() {
  if (addColor) this.style.color = "red";
  if (this.id === "special") addColor = true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <p>Test</p>
  <p>Test</p>
  <p id="special">Test</p>
</div>
<p>Test</p>
<p>Test</p>
<div>
  <div>
    <p>Test</p>
  </div>
</div>

答案 4 :(得分:0)

您可以使用CSS ~选择器。

在你的情况下:

p#special ~ p