2

Is this possible with CSS? I want to only display the first instance of an unknown class, or do I need to use Javascript?

<div class="agendaDay apr24">24 April</div>
<div class="agendaDay apr24">24 April</div>
<div class="agendaDay apr25">25 April</div>
<div class="agendaDay apr26">26 April</div>

Desired output:

<div class="agendaDay apr24">24 April</div>
<div class="agendaDay apr24" style="display:none">24 April</div>
<div class="agendaDay apr25">25 April</div>
<div class="agendaDay apr26">26 April</div>

Basically. I won't know what the class name is, but wondering if there's someway I can select potentially repeating class names using css.

cimmanon
  • 67,211
  • 17
  • 165
  • 171
TweakItGuy
  • 21
  • 2

4 Answers4

0

How about this?

.apr24:nth-child(2){
   display: none;
}

With css3 you can do this:

div[class*="apr24"]:nth-child(2){
    display: none;
}

that mean is if a div has the class apr24 do something.

0

If you know the class name (which is not the specific case), you can use a trick with :first-of-type selector,

.apr24 {display: none}
.apr24:first-of-type {display: block}

Fiddle

However, if you're allowed to use javascript eventually, you can use :contains to target a specific text and display the first one. Like this :

$('div:contains("24 April")').hide().first().show();

Fiddle with js possibility

Vincent G
  • 8,547
  • 1
  • 18
  • 36
0

Thank you, as not being able to do this via CSS, here is my solution in JS.

$(".agendaDay").each(function(i, obj) {
    if(i>0){
        if($(".agendaDay:eq("+i+")").attr("rel") == $(".agendaDay:eq("+(i-1)+")").attr("rel")){
                    $(".agendaDay:eq("+i+")").attr("hidden","hidden");
        }
    }
}

After rendering the page, I am looking through each div, if the "rel" attribute of the previous div equals the current one then I am hiding the current div.

TweakItGuy
  • 21
  • 2
0

You can, if you know the class names, do something similar:

.apr24 {
    display: block;
}

.apr24 ~ .apr24 {
    display: none;
}

The ~ CSS selector picks all siblings, which you can hide.


I assume that you're doing some logic on the backend when generating your list of agenda HTML, so if you're using SCSS/LESS then you could do:

# HTML
<section class="agendaMonth">
    <div class="agendaDay d24">24 April</div>
    <div class="agendaDay d24">24 April</div>
    <div class="agendaDay d25">25 April</div>
    <div class="agendaDay d26">26 April</div>
</section>

And the CSS can be generated like this:

# SCSS
@for $i from 1 through 31 {
    SECTION.agendaMonth DIV.d#{$i} ~ DIV.d#{$i} {display: none;}
}

The reason you need the SECTION-tag is to "interrupt" the sibling-selector, so it doesn't target d24 in any later months.

Hope this helps.

kunambi
  • 756
  • 1
  • 10
  • 25