Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/CSS - How to style the first occurrence of an element inside of another element?

Tags:

html

jquery

css

Here's my problem.

HTML

<div id="content">
    <h1>Headline</h1>
    <p>First paragraph that needs to be yellow.</p>
    <p>Second paragraph that need not change. :) </p>
    <p>Third paragraph that need not change. :) </p>
</div>

If I use #content p:first-child {color:yellow; } it doesn't work because p isn't the first-child of content... h1 is the first born.

How can I do this without touching the HTML code?

Thank you!

All the best, Cris

like image 282
Cris Avatar asked Apr 19 '11 20:04

Cris


People also ask

How do you target the first element in CSS?

The :first-of-type selector in CSS allows you to target the first occurence of an element within its container. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.

How do you select an element after an element in CSS?

If you want to select an element immediately after another element you use the + selector.

How do I select the first div inside a div?

Using the :first-child selector, you can target or select the very first element inside an element, like a DIV. You can use any other element as a container like <section> or <article> etc.

How do you select the first paragraph in CSS?

CSS ::first-line Selector The ::first-line selector is used to add a style to the first line of the specified selector. Note: The following properties can be used with ::first-line: font properties. color properties.


5 Answers

a css3 solution

#content > p:first-of-type { color: yellow; }
like image 130
ohmusama Avatar answered Oct 21 '22 21:10

ohmusama


This is the best way:

$('#content p:first').css('color', 'yellow');
like image 34
Naveed Ahmad Avatar answered Oct 21 '22 19:10

Naveed Ahmad


you can use also (CSS, jQuery) nth-of-type:

#content p:nth-of-type(1) {color:yellow; }

$('#content p:nth-of-type(1)').css('color', 'yellow');
like image 4
manji Avatar answered Oct 21 '22 19:10

manji


Use the .first() function (or :first selector) instead:

$('#content > p').first().css('color', 'yellow');
like image 3
Alnitak Avatar answered Oct 21 '22 20:10

Alnitak


<script>
$(function(){
    $('#content p:first').css('color','yellow');
});
</script>
like image 2
Vismari Avatar answered Oct 21 '22 21:10

Vismari