javascript - How to select the paragraph with only specific class - Stack Overflow

Let say I have my HTML code look like this:<p class="p">Paragraph<p><p class

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?

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?

Share Improve this question asked Apr 28, 2013 at 15:40 user2329398user2329398 2
  • 1 possible duplicate of jQuery: Is it possible to select elements with only one class from among elements with, potentially, up to 3 classes? – user1106925 Commented Apr 28, 2013 at 15:44
  • Why are you counting your ps? – melhosseiny Commented Apr 28, 2013 at 23:15
Add a ment  | 

4 Answers 4

Reset to default 4

You can use attribute selector:

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

http://jsfiddle/umxGh/

Or:

$('p').filter(function(){
   return this.className === 'p';
}).css('color', 'red');

You can use:

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

or:

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

Fiddle

Use an attribute selector:

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

Try this:

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743750231a4500762.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信