0

I have this HTML setup:

<div class="main">
  <div>
    <div class="image"></div>
  </div>
  <div class="text"></div>
  <div class="text"></div>
  <div>
    <div class="image"></div>
  </div>
</div>

With CSS, is it possible to hide all of the child elements of ".main" except the first classless div that contains the ".image" class div?

BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
Weebs
  • 135
  • 1
  • 10

3 Answers3

1

Do you absolutely require the "contains an .image" condition? If so, you won't be able to do this since there is no parent selector (see also How do I select an element based on the state of another element in the page with CSS?).

If every classless child element of .main is guaranteed to contain an .image and every child element that has a class is guaranteed not to do so, write selectors based on this assumption instead, since you won't be able to construct selectors based on the "contains an .image" condition. Use a sibling combinator to exclude the first classless element:

.main > div[class], .main > div:not([class]) ~ div:not([class]) {
  display: none;
}

But if — and this seems likely — not every classless element is guaranteed to contain an .image or not every element that has a class is guaranteed not to do so, the answer loops back to "not possible with pure CSS".

BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
0

Yes, you can use this css selector :not(:first-child)

.main div:not(:first-child) {
    display: none;
}
<div class="main">
  <div>
    <div class="image">This should be visible</div>
  </div>
  <div class="text">This should be hidden</div>
  <div class="text">This should be hidden</div>
  <div>
    <div class="image">This should be hidden</div>
  </div>
</div>
SunriseM
  • 865
  • 8
  • 14
  • Yes, I considered this route, but in some cases, the div containing ".image" may not always be the first child and I need the first element that contains ".image" to be visible. – Weebs Jan 06 '18 at 03:53
-2

Don't Forgot to use jquery

give all (.c1) class to all inner elements of (.main) class

index.html

<div class="main">
  <div class="c1">
    <div class="image"></div>
  </div>
  <div class="c1 text"></div>
  <div class="c1 text"></div>
  <div class="c1">
    <div class="image"></div>
  </div>
</div>
<script>
  $(document).ready(function(){
    $('.c1').hide();
    $('.c1:first').show();
  });
</script>