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

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

Answers


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

<script>
$(function(){
    $('#content p:first').css('color','yellow');
});
</script>

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

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

EDIT:

$("#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 () {
              $(this).addClass("sogreen");
            }, function () {
              $(this).removeClass("sogreen");
            });

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