【问题标题】:Select element based on the child of its previous sibling根据其前一个兄弟的子元素选择元素
【发布时间】:2016-09-27 21:02:48
【问题描述】:

我有这个代码:

<cite>
 <a id="john" href="javascript: void(0)">John</a>
 <span>time</span>
 <a>DELETE</a>
</cite>
<blockquote>hello there</blockquote>

这是我的 CSS:

cite #john + blockquote {color:black;}

我知道这行不通,但我需要在包含 ID 为 john 的锚点的 cite 之后仅选择 blockquote 元素。

我不能只更改 CSS 的 HTML。请问有什么想法吗?

如果 CSS 无法做到这一点,那么 JavaScript 解决方案也将受到欢迎。

【问题讨论】:

标签: javascript css css-selectors


【解决方案1】:

您可以使用以下 jQuery 选择器来选择所需的元素。

$('cite').has('a#john').next('blockquote')

$('cite').has('a#john').next('blockquote').addClass('active');
.active {
  background: green;
}

blockquote {
  margin-right: 0;
  margin-left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<cite>
  <a id="john" href="javascript: void(0)">John</a>
  <span>time</span>
  <a>DELETE</a>
</cite>
<blockquote>hello there</blockquote>
<cite>
  <a href="javascript: void(0)">John</a>
  <span>time</span>
  <a>DELETE</a>
</cite>
<blockquote>hello there</blockquote>
<cite>
  <a id="john" href="javascript: void(0)">John</a>
  <span>time</span>
  <a>DELETE</a>
</cite>
<blockquote>hello there</blockquote>

没有 jQuery 的解决方案:

var activeClass = 'active';
var cites = document.querySelectorAll('cite');

[].forEach.call(cites, function(elem) {
	if(elem.querySelector('a#john')) {
        var blockQuote = elem.nextElementSibling;
        blockQuote.className = blockQuote.className + activeClass;
    }
});
.active {
  background: green;
}

blockquote {
  margin-right: 0;
  margin-left: 0;
}
<cite>
  <a id="john" href="javascript: void(0)">John</a>
  <span>time</span>
  <a>DELETE</a>
</cite>
<blockquote>hello there</blockquote>
<cite>
  <a href="javascript: void(0)">John</a>
  <span>time</span>
  <a>DELETE</a>
</cite>
<blockquote>hello there</blockquote>
<cite>
  <a id="john" href="javascript: void(0)">John</a>
  <span>time</span>
  <a>DELETE</a>
</cite>
<blockquote>hello there</blockquote>

【讨论】:

  • 没有jquery可以吗?好像不能在这里用。
  • 对不起,现在我得到这个:cites.forEach 不是一个函数”,
  • @CainNuke 您在哪个浏览器中查看?
  • 我在火狐上。 jquery 代码显示正常,但不是第二个。
  • @CainNuke 我再次更新了,请检查一下,它应该可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-26
  • 1970-01-01
  • 2015-01-14
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
相关资源
最近更新 更多