-3

Like for example: Suppose I want to give color to the second paragraph.

<div class="intro">
    <p>My name is Donald</p>
    <p>I live in Duckburg</p>
    <p>I have many friends:</p>
</div>

How can I only Select the second paragraph in CSS as well as jQuery as no name or ids are assigned two them.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Riya
  • 21
  • 1
  • 1
  • 4
    In CSS use `:nth-child(2)`, in jQuery use `eq(1)` – Rory McCrossan Nov 18 '16 at 14:36
  • Demo: https://jsfiddle.net/szq7onru/ – Andrew Li Nov 18 '16 at 14:37
  • 1
    @Rory - `.intro p:nth-of-type(2)`, _not_ `.intro p:nth-child(2)` (!) Otherwise subsequent revisions of the document (eg. inserting an `img` between the first and second paragraphs) will mean the style no longer works, because the second child will no longer be a `p`. – Rounin Nov 18 '16 at 14:42
  • Well yes. There's an infinite number of ways to change the solution if you want to invent new HTML markup. All I can do is give an answer based on what the OP has shown. – Rory McCrossan Nov 18 '16 at 14:51

2 Answers2

3

You can try this:

$(".intro p:nth-child(2)");
// OR
$(".intro p:eq(2)");

See Code Block below:

$(".intro p:nth-child(2)").css("background-color", "red");
// OR
// $(".intro p:eq(1)");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="intro">
    <p>My name is Donald</p>
    <p>I live in Duckburg</p>
    <p>I have many friends:</p>
</div>

Hope this helps!

Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
0

This code will work for CSS:

.intro p:nth-of-type(2) {
  color: blue; 
}

It'll pick only the second paragraph and add blue color to it