根据其先前同级的子元素选择元素 [英] Select element based on the child of its previous sibling

查看:44
本文介绍了根据其先前同级的子元素选择元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

<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;}

我知道这是行不通的,但是我需要一些选择来仅选择cite元素之后的cite元素,该元素包含ID为john的锚点.

I am aware this won't work but I need something to select only the blockquote elements right after a cite that contains an anchor with the ID john.

我不能仅更改CSS的HTML.有什么想法吗?

I cannot change the HTML only the CSS. Any ideas please?

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

If this is impossible with CSS then a JavaScript solution would be welcome too.

推荐答案

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

You can use following jQuery selector to select the desired element.

$('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>

这篇关于根据其先前同级的子元素选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆