在第一个div中添加一个类来设置内部div?

时间:2016-04-13 14:11:30

标签: javascript jquery html css

我有一个动态生成的元素列表,除了第一个元素之外,它们的样式都是相同的。如果第一个没有呈现,我希望第二个(现在是第一个)具有第一个样式。

  <div class="container">
    <a><div>first</div></a>
    <a><div>second</div></a>
    <a><div>third</div></a>
    <a><div>fourth</div></a>
    </div>

我尝试仅使用CSS,但它没有所需的结果。

.container a:first-child div{
background:red;
}

我还尝试通过jquery向第一个div添加一个类,但它甚至没有添加我的类:

$('.container a:first div').addClass('aaaa');

由于这些方法似乎都不起作用,我怎样才能完成我想做的事情?主要是想修复我的CSS答案,但如果不可能,jquery也会起作用。

使用案例

我正在构建一种计划配置文件,但由于我们的框架不支持日历窗口小部件,我们填写数据,然后使用Date.parse() / moment.js来获取时间戳。然后,我们将日期(即2016年6月1日)与当前日期的时间戳进行比较。 if current date > event-date然后事件日期不会呈现。

我们最多可存储4个活动日期,并且我正在努力使其自行折旧,因此我们无需在每次活动完成时更新它。

呈现HTML的示例:

<div class="container events" style="margin-top: 28px;">
  <h3>Upcoming Meetups</h3>
  <div class="hugs-post-instructions">blah blah<br>Click on each button to be taken to the registration page.</div>

  <a href="#">
    <div class="square-button">Next Meetup: May 19, 2016
    </div>
  </a>

  <a href="#">
    <div class="square-button">Upcoming Meetup: September 22, 2016
    </div>
  </a>

  <a href="#">
    <div class="square-button">Upcoming Meetup: December 1, 2016
    </div>
  </a>
</div>

2 个答案:

答案 0 :(得分:3)

啊,根据您的更新,我相信您希望:nth-of-type伪类作为您的选择器:

.container a:nth-of-type(1) div {
  background: red;
}
<div class="container events" style="margin-top: 28px;">
  <h3>Upcoming Meetups</h3>
  <div class="hugs-post-instructions">blah blah
    <br>Click on each button to be taken to the registration page.</div>

  <a href="#">
    <div class="square-button">Next Meetup: May 19, 2016
    </div>
  </a>

  <a href="#">
    <div class="square-button">Upcoming Meetup: September 22, 2016
    </div>
  </a>

  <a href="#">
    <div class="square-button">Upcoming Meetup: December 1, 2016
    </div>
  </a>
</div>

:first-child伪类只选择那个作为其父元素的第一个子元素的元素,而不是特定种类的第一个子元素,这就是为什么这对你不起作用。

答案 1 :(得分:0)

或者,您可以突出显示第一个div,为他们提供所有红色背景,然后将其移除所有adjacent siblings

&#13;
&#13;
.container a div {
    background:red;
}
.container a + a div {
    background:inherit;
}
&#13;
<div class="container events" style="margin-top: 28px;">
  <h3>Upcoming Meetups</h3>
  <div class="hugs-post-instructions">blah blah<br>Click on each button to be taken to the registration page.</div>

  <a href="#">
    <div class="square-button">Next Meetup: May 19, 2016
    </div>
  </a>

  <a href="#">
    <div class="square-button">Upcoming Meetup: September 22, 2016
    </div>
  </a>

  <a href="#">
    <div class="square-button">Upcoming Meetup: December 1, 2016
    </div>
  </a>
</div>
&#13;
&#13;
&#13;

相关问题