【问题标题】:Select an element in DOM which is not a sibling, but goes after在 DOM 中选择一个元素,它不是同级元素,但在后面
【发布时间】:2019-03-25 04:22:47
【问题描述】:

假设我有以下 DOM

<div class="parent">
   <div class="childNotSibling">
   </div>
</div>

<div class="elementToSelect">
</div>

现在我想选择带有 elementToSelect 类的 div,但前提是带有 parent 类的 div 里面有一个带有 childNotSibling 类的元素。是否可以使用 css 完成此操作?

【问题讨论】:

  • 您是在问是否可以在纯 CSS 或 Javascript 的帮助下完成此任务?
  • 很遗憾,没有使用 CSS(需要 JavaScript)。
  • 用javascript,很简单。 CSS,不可能。或许你可以使用javascript给elementToSelect添加一个类,例如添加一个名为elementSelected的类,然后使用CSS来选择.elementSelected
  • @tremor,我对纯 CSS 很感兴趣。但根据我的问题,JavaScript 也可以。无论如何,如果您确定没有使用 css 的解决方案,我会很高兴看到 JavaScript 解决方案。

标签: html css dom select css-selectors


【解决方案1】:

这个 JSFiddle 应该可以解决问题:https://jsfiddle.net/tremor/f4cghd5x/

这里使用 JQuery 是代码的 Javascript 部分。

// find all the occurrences of .childNotSibling
$("body").find(".childNotSibling").each(function(index, element) {
  // if .childNotSibling's parent has class "parent"
  if ($(this).parent().hasClass("parent")) {
    // and if the parent's next sibling has "elementToSelect"
    if ($(this).parent().next().hasClass("elementToSelect")) {
      // do something with that element
      $(this).parent().next().css("background-color", "red");
    }
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-20
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    相关资源
    最近更新 更多