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

Here's my problem.


<div id="content">
    <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>

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


This is the best way:

$('#content p:first').css('color', 'yellow');

a css3 solution

#content > p:first-of-type { color: yellow; }

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');

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

$('#content > p').first().css('color', 'yellow');

    $('#content p:first').css('color','yellow');

Since you have tagged it using jQuery, jQuery based solution:

$("#content p:first-child").css({color:"yellow;" });


$("#content p:nth-child(2)").css({color:"yellow" });

$('#content p').first().css({ color: 'yellow' });

Try this:

$("div p:first")
        .css("text-decoration", "underline")
        .hover(function () {
            }, function () {

With just CSS, you could use the sibling selector + like so:

#content h1 + p { color: yellow; }

This would only change paragraphs immediately following H1s.

Need Your Help

How to download file in swift?

ios swift file download

I just started learning apple swift programming for iOS coming from android. I basically can now read and manipulate swift code and also learned some common classes used in iOS swift programming but