根据其先前兄弟的子元素选择元素

时间:2016-09-26 15:56:18

标签: javascript css css-selectors

我有这段代码:

<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为blockquote的锚的cite之后立即选择john元素。

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

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

1 个答案:

答案 0 :(得分:3)

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

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

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

blockquote {
  margin-right: 0;
  margin-left: 0;
}
&#13;
<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>
&#13;
&#13;
&#13;

没有jQuery的解决方案:

&#13;
&#13;
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;
    }
});
&#13;
.active {
  background: green;
}

blockquote {
  margin-right: 0;
  margin-left: 0;
}
&#13;
<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>
&#13;
&#13;
&#13;