我有这段代码:
<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解决方案。
答案 0 :(得分:3)
您可以使用以下jQuery选择器来选择所需的元素。
$('cite').has('a#john').next('blockquote')
$('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;
没有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;
}
});
&#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;