2

Most of my pages have H2's and obviously an H1.

The H2's can be inside divs/articles/sections etc - in other words there is no guaranteed structure.

Here's a typical scenario:

<h1></h1>
<section>
    <h2>I want this one</h2>
    <p></p>
</section>
<section>
    <h2>But not this one</h2>
    <p></p>
</section>

I want a selector that always guarantees the first occurance on the page - in this case the first H2 wherever it maybe.

I've taken a look and tried the first-of-type selector but found that it applies to its own container, so every H2 is selected here because it is the first within its parent section tag.

Surely in 2015, we are able to do this.

web-tiki
  • 99,765
  • 32
  • 217
  • 249
John Ohara
  • 2,821
  • 3
  • 28
  • 54
  • I am not sure that there a selector with the functionality you seek exists, but you could use the the first-of-type selector if all of your `

    ` exist inside `
    `. Would that work for you?

    – Tasos K. Apr 29 '15 at 08:38
  • They do in this scenario, but I would have to map a selector specifically for every page variation where the structure differed, so not exactly efficient css. – John Ohara Apr 29 '15 at 08:40
  • 2
    @JohnOhara I think that Javascript would be your best bet here, I can't think of a way to do this via CSS only. – Ruddy Apr 29 '15 at 08:47
  • 3
    "Surely in 2015, we are able to do this."...Nope...Javascript is the **only** solution in this instance. – Paulie_D Apr 29 '15 at 09:04

2 Answers2

1

Use jquery. Honestly i tried css only methods, but failed. Excellent question btw.

<script>
$(document).ready(function(){
$( "h2:first" ).css( "color", "red" );
});

</script>
majorhavoc
  • 2,385
  • 1
  • 24
  • 26
-1

you could simply use the css selector first-of-type

Definition and Usage The :first-of-type selector matches every element that is the first child, of a particular type, of its parent.

Tip: This is the same as :nth-of-type(1).

h2:first-of-type {
    color: red;
}

or as a jQuery solution:

$('h2').first().css('color','red');
Doml The-Bread
  • 1,761
  • 1
  • 11
  • 17