7

Let say I have my HTML code look like this:

<p class="p">Paragraph</p>
<p class="p p2">Paragraph 2</p>
<p class="p p3">Paragraph 3</p>

If I use: $('.p').css('color','red'), this will apply red color to all paragraphs.

How can I apply the style to paragraph that only has class p which is first paragraph in this case?

  • 1
    possible duplicate of [jQuery: Is it possible to select elements with only one class from among elements with, potentially, up to 3 classes?](http://stackoverflow.com/questions/8512111/jquery-is-it-possible-to-select-elements-with-only-one-class-from-among-element) –  Apr 28 '13 at 15:44
  • Why are you counting your `p`s? – melhosseiny Apr 28 '13 at 23:15

4 Answers4

4

You can use attribute selector:

$('p[class="p"]').css('color','red');

http://jsfiddle.net/umxGh/

Or:

$('p').filter(function(){
   return this.className === 'p';
}).css('color', 'red');
Ram
  • 143,282
  • 16
  • 168
  • 197
3

You can use:

$('.p[class="p"]').css('color', 'red');

or:

$("p[class='p']").css('color', 'red');

Fiddle

Eli
  • 14,779
  • 5
  • 59
  • 77
3

Use an attribute selector:

$('p[class="p"]').css('color','red')
Adrift
  • 58,167
  • 12
  • 92
  • 90
0

Try this:

$('[class=p]').css('color','red');
BYTE RIDER
  • 169
  • 2
  • 12