排除具有特定子元素的元素

时间:2020-06-03 13:33:23

标签: html jquery css

在我(Tumblr)网站上的帖子上,我有很多段落,其中一些放在大括号内。在出现块引用的位置,其上方的段落通常是第一段(尽管多个块引用将意味着其中的多个)通常只有一个链接子项,而内部没有其他内容。例如:

<p> <a class="foo"> Link name </a> </p>
<blockquote>
    <p> If there were multiple nested blockquotes, each one would have a <p><a class="foo"> line atop each new blockquote. </p>
    <p> Some more text </p>
</blockquote>
<p> Some more text. </p>
<p> Even more text. </p>

我如何设置所有段落的样式(添加底部填充),除了那些具有单个链接子代的段落(我想与blockquote齐平放置-没有/最小的填充或边距)?大概“:not()”可以工作,但是我还没有弄清楚在括号内使用的正确选择器。

2 个答案:

答案 0 :(得分:0)

要为<p>元素的后代(不仅是直接后代)的所有<blockquote>元素设置样式,可以使用如下所示的CSS选择器。

blockquote p {
  color: red;
}
<p>Selector doesn't apply to me.</p>
<blockquote>
  <p>Selector applies to me.</p>
  <p>And me.</p>
  <footer>
    <p>And also me.</p>
  </footer>
</blockquote>

答案 1 :(得分:0)

在jQuery中使用:has():not() CSS伪类选择器可以实现您想要的。 :有()选择器 不能在CSS样式表中使用。

$(document).ready(function() {
  var pElements = $(':not(p:has(> a))');
  pElements.css('padding-bottom', '20px');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<p> <a class="foo"> Link name </a> </p>
<blockquote>
  <p> Some text </p>
  <p> Some more text </p>
</blockquote>
<p> Some more text. </p>
<p> Even more text. </p>

更新:包括<article class='post'>

$(document).ready(function() {
  var pElements = $('article.post :not(p:has(> a))');
  pElements.css('padding-bottom', '20px');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<article class="post">
  <p> <a class="foo"> Link name </a> </p>
  <blockquote>
    <p> Some text </p>
    <p> Some more text </p>
  </blockquote>
  <p> Some more text. </p>
  <p> Even more text. </p>
</article>

<p> P element out of class post </p>
<p> P element out of class post </p>
<p> P element out of class post </p>
<p> P element out of class post </p>
<p> P element out of class post </p>

相关问题