ʞɹᴉʞ ǝʌɐp
ʞɹᴉʞ ǝʌɐp

Reputation: 5650

How to change class name of all elements without iteration?

I have a DOM structure like this: (using jQuery)

<div class="test page-1">some code and more dom</div>
<div class="test page-2">some code and more dom</div>
<div class="test page-3">some code and more dom</div>
<div class="test page-4">some code and more dom</div>
<div class="test page-5">some code and more dom</div>
<div class="test page-6">some code and more dom</div>
<div class="test page-7">some code and more dom</div>

and few more ....

Now, how can I increase the number suffixing classes like page-1, page-2 etc. by n (e.g. by 1) so that resulting class becomes page-2, page-3 etc. ?

i.e. only number of class page-1 will increase and page-1 class becomes page-2

One way is to iterate through all elements using class test and remove the class and add the new one.

Is there a better way to achieve this for more performance?

The use case is where I have to insert page in between the divs so the inserted page becomes the current page and page's number after that will increase by 1.

Upvotes: 1

Views: 427

Answers (3)

MD SHAHIDUL ISLAM
MD SHAHIDUL ISLAM

Reputation: 14523

Use:

$(".test").each(function(index, element) {
     var classes = $(this).attr("class");
     var splitted = classes.split("-")[1];
     classes = classes.replace(splitted,String(parseInt(splitted)+1));
     $(this).removeAttr('class').addClass(classes);
});

Upvotes: 0

LeGEC
LeGEC

Reputation: 51932

The short answer is no. Even if you wanted to add the same class to all elements, the loop would be hidden inside the $('.test').addClass('myClass') call.

You could use a data-page attribute, use jQuery's .data() function, or not add anything and use $(this).index() or the loop counter to have a page number :

 $('.test').each(function(i) {
      // i is the page number ...
 });

 // accessing the i-th element :
 $('.test')[i];

Upvotes: 4

HarryFink
HarryFink

Reputation: 1010

Try this one:

$("[class*='page-']").each(function(){
    var 
    newClass,
    classParts,
    currentClass = $(this).attr('class');
    classParts = currentClass.split('-');
    newClass = classParts[0] +'-'+ (parseInt(classParts[1])+1);
    $(this).attr('class', newClass)
})

Upvotes: 0

Related Questions