TransWikia.com

Apply a common class to html tags based on some condition using jquery

Stack Overflow Asked by Ityka Bandta on August 18, 2020

I have something like this –

<body>
<p >PARA1</p>
<p >PARA2</p>
<p>PARA3</p>
<p>PARA4</p>
<p>PARA5</p>
<p>PARA6</p>
<button>REMOVE</button>
</body>

I want to add ‘new’ class to the all the paragraphs after the 4th one using Jquery. My code-

$.each($('p').index > 4, function() {
                              $('p').addClass('new')
                            });

Can anyone please tell me how to fix this code?

4 Answers

In case you want to use loop for doing more operations along with adding new class.

$('p').each((i, para) => {
  if (i > 3) {
    $(para).addClass('new')
    // some other operations
  }
})
.new {
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<body>
    <p>PARA1</p>
    <p>PARA2</p>
    <p>PARA3</p>
    <p>PARA4</p>
    <p>PARA5</p>
    <p>PARA6</p>
    <button>REMOVE</button>
</body>

Answered by Guryash Singh on August 18, 2020

The slice method allows you to select all elements greater than or equal to the provided index.

$('p').slice(4).addClass('new');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<body>
    <p>PARA1</p>
    <p>PARA2</p>
    <p>PARA3</p>
    <p>PARA4</p>
    <p>PARA5</p>
    <p>PARA6</p>
    <button>REMOVE</button>
</body>

Answered by Andrew Arthur on August 18, 2020

You can use the :nth-child(n+5) pseudo-selector to select the 4th child onward:

$('p:nth-child(n+5)').addClass('new');

Using nth-child to style item 4 and onwards

Answered by kmoser on August 18, 2020

You can try

  $("p").slice(4).addClass("new");

The slice filter selects a sub-array starting the nth element of the returned jquery objects

https://api.jquery.com/slice/

Answered by Massimo on August 18, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP